﻿#include "mainwindow.h"
#include "Template/singleton.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTextEdit>

#include <QtCharts/QChartView>



#include <QTimer>
#include <QScatterSeries>
#include <QSerialPortInfo>
#include <QValueAxis>
#include <QColor>
#include <QFileDialog>
#include <QToolBar>
#include <QLegendMarker>
#include <QDesktopWidget>
#include "TabWidget/deviceconfigtab.h"
#include "TabWidget/devicechartstab.h"
#include "CTDWidget/dockwidgetctd.h"
#include "CTDWidget/dockwidgetctd_imcharts.h"

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#include <QMessageBox>



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,ui(new Ui::MainWindow)
    ,confirmDevice(ConfirmDeviceInstance)
    ,deviceConfigTab(DeviceConfigTabInstance)
    ,deviceChartsTSC(DeviceChartsTSCInstance)
    ,dockWidgetCTD_IM(DockWidgetCTDInstance)
    ,m_Heart_timer(new QTimer(this))
    ,m_bFirstSampling(true)
    , m_dMaxT(0)
    , m_dMinT(0)
    , m_dMaxP(0)
    , m_dMinP(0)
    , m_bGetFlash(false)
    , m_pDialog(NULL)
    , m_start_rotate (new QPushButton())
{
    ui->setupUi(this);

    // 发送串口丢失
    connect(confirmDevice, &ConfirmDevice::sendComRemove_TDSC_Signal, this, &MainWindow::reciveTDSCComName);

    connect(confirmDevice, &ConfirmDevice::sendComRemove_TSC_Signal, deviceConfigTab, &DeviceConfigTab::reciveComNameTSC);
    connect(confirmDevice, &ConfirmDevice::sendComRemove_TSC_Signal, deviceChartsTSC, &DeviceChartsTSC::recvComPullOut);
    connect(confirmDevice, &ConfirmDevice::sendComRemove_TSC_Signal, this, &MainWindow::reciveTSCComName);

    connect(confirmDevice, SIGNAL(sendStopTimer()), this, SLOT(setStopTimer()));
    
    connect(confirmDevice,SIGNAL(sendTypeData(Message_t)),this,SLOT(HandleTypeData(Message_t)));


    // TD TemperatureCoefficientAB
    connect(this,SIGNAL(sendTemperatureCoefficient(QByteArray,QByteArray)),confirmDevice,SLOT(setTemperatureCoefficientABCD(QByteArray,QByteArray)));

    // TD sendTemperatureCD
    connect(this,SIGNAL(sendTemperatureCD(QByteArray)),confirmDevice,SLOT(reciveTemperatureCD(QByteArray)));
 
    // TD sendPressureCoefficientAB
    connect(this,SIGNAL(sendPressureCoefficientAB(QByteArray)),confirmDevice,SLOT(recivePressureCoefficientAB(QByteArray)));

    // TD send_Pressure_CoefficientCD
    connect(this,SIGNAL(send_Pressure_CoefficientCD(QByteArray)),confirmDevice,SLOT(recive_Pressure_CoefficientCD(QByteArray)));

    // TD send_Pressure_CoefficientCD
    connect(this,SIGNAL(send_Calibration_Time(QByteArray)),confirmDevice,SLOT(recive_Calibration_Time(QByteArray)));

    // TD send_Get_Calibration_Coefficient
    connect(this,SIGNAL(send_Get_Calibration_Coefficient()),confirmDevice,SLOT(send_Calibration_Coefficien()));

    // TD send_Start_Sample
    connect(this,SIGNAL(send_Start_Sample(QByteArray)),confirmDevice,SLOT(recive_Start_Sample(QByteArray)));

    // TD send_Signal_PresureAB_From_Device
    connect(confirmDevice,SIGNAL(send_Set_Btn_Status(QByteArray)),this,SLOT(set_Btn_Status(QByteArray)));

    // TD send_Start_Sample
    connect(this,SIGNAL(send_Stop_Sample()),confirmDevice,SLOT(recive_Stop_Sample()));

    // TD send_Signal_PresureAB_From_Device
    connect(confirmDevice,SIGNAL(send_Stop_After_Change_Status()),this,SLOT(set_Stop_After_Change_Status()));

    // TD send_Start_Sample
    connect(this,SIGNAL(send_Read_Sample_Status()),confirmDevice,SLOT(get_Sample_Status()));

    // TD 获取上次配置
    connect(this,SIGNAL(send_Get_Sample_Config()),confirmDevice,SLOT(send_Read_Sample_Config()));

    // TD 获取上次配置
    connect(this,SIGNAL(send_Read_Flash()),confirmDevice,SLOT(send_Read_Flash_Using_DownLoad()));

    //connect(confirmDevice,SIGNAL(send_Flash_Info(QByteArray,QByteArray)),this,SLOT(set_Down_Load(QByteArray,QByteArray)));
    connect(confirmDevice,SIGNAL(send_Flash_Info(QByteArray)),this,SLOT(set_Down_Load(QByteArray)));

    // TD 获取上次配置
    connect(this,SIGNAL(send_Once_Sample()),confirmDevice,SLOT(send_Once_Sample()));
  

    // TD 设备时间实时更新
    // m_Heart_timer->start(500);
    connect(m_Heart_timer,SIGNAL(timeout()),confirmDevice,SLOT(get_Sample_Status()));

    init_Layout();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init_Layout()
{
    // 隐藏表头
    ui->treeWidget->setHeaderHidden(true);
    // 删除中央窗体,填充主界面
    QWidget* p = takeCentralWidget();
    if(p)
        delete p;

    // 允许嵌套 dock
    setDockNestingEnabled(true);

    // 设置状态栏黄色
    ui->m_labelStatus->setStyleSheet("QLabel{background:#ffff00; border-radius: 8px;}");
    // 时间编辑栏显示 年月日时分秒
    ui->m_dateTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    ui->m_dateTimeEdit_End->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    ui->m_spinBox_Hour->setRange(0,23);
    ui->m_spinBox_Minute->setRange(0,59);
    ui->m_spinBox_Second->setRange(0,59);
    ui->m_proBar_Memory->setStyleSheet("QProgressBar{border-radius:5px;border:1px;background:rgb(0, 255, 0);} QProgressBar::chunk{border-radius:5px;background:rgb(255, 127, 0)}");
    //ui->m_proBar_Memory->setFormat("已使用内存%24");
    ui->m_proBar_Memory->setFormat(QString("已使用内存 %%1").arg((100 * m_iPageQuantity / 524288) == 0 ? 1: (100 * m_iPageQuantity / 524288)));
    ui->m_proBar_Memory->setAlignment(Qt::AlignLeft | Qt::AlignCenter);
    ui->m_combomBox_Coefficient->setCurrentIndex(0);

    for(int index=0;index<4;index++)
    {
        ui->m_tableWidget_CalibrationT->item(index,0)->setFlags(ui->m_tableWidget_CalibrationT->item(index,0)->flags()&~Qt::ItemIsEditable);
        //  设置字体
        // ui->m_tableWidget_CalibrationT->item(index,0)->setFont(QFont("微软雅黑",9,QFont::Normal));
        // 设置字体颜色
        // ui->m_tableWidget_CalibrationT->item(index,0)->setTextColor(Qt::darkGray);
        // 设置 背景色
        // ui->m_tableWidget_CalibrationT->item(index,0)->setBackground(QBrush(QColor(Qt::lightGray)));
    }
    //ui->m_tableWidget_CalibrationT->setStyleSheet("selection-background-color: #cce8ff");
    ui->m_tableWidget_CalibrationT->setFocusPolicy(Qt::NoFocus);

    // set_Bar_WidgetCenter(this);
    //表头标题用QStringList来表示
    QStringList headerText;
    headerText<<"标 签"<<"数 值";
    ui->m_tableWidget_CalibrationT->setHorizontalHeaderLabels(headerText);
    ui->m_tableWidget_CalibrationT->setColumnWidth(1,230);
    //设置最后一栏自适应长度
    ui->m_tableWidget_CalibrationT->horizontalHeader()->setStretchLastSection(true);

    QDockWidget* navDock=ui->dockWidget_1;
    configDock=ui->dockWidget_2;
    Bottom_Dock_Chart=ui->dockWidget_3;

    this->setWindowIcon(QIcon(":/Image/SeaStream.png"));
    this->setFont(QFont("Microsoft YaHei UI", 8, 70));
    this->setWindowTitle("OceanPlot-Talk v1.3.1");
    navDock->setFeatures(QDockWidget::DockWidgetMovable);
    navDock->setAllowedAreas(Qt::LeftDockWidgetArea);
    navDock->setFont(QFont("Microsoft YaHei UI", 8, 70));
    navDock->setWindowTitle(tr("导航窗口"));
    navDock->setMaximumWidth(300);
    navDock->setMinimumWidth(150);
    navDock->setMinimumHeight(600);

    m_tabWidget = ui->tabWidget;
    m_tabWidget->setTabText(0,"配置");
    m_tabWidget->setTabText(1,"信息");
    m_tabWidget->setTabText(2,"校准");
    m_tabWidget->setTabText(3,"参数");
    // 设置按钮不可用
    m_tabWidget->setTabEnabled(3,false);
    m_tabWidget->setTabToolTip(3,QString("正在开发中"));
    m_tabWidget->setCurrentIndex(0);

    ui->label_type->setText("Oceanplot-TD");

    configDock->setFeatures(QDockWidget::DockWidgetMovable);
    configDock->setAllowedAreas(Qt::RightDockWidgetArea);
    configDock->setFont(QFont("Microsoft YaHei UI", 8, 70));
    configDock->setWindowTitle(tr("TD-SC"));
    //configDock->hide();
    //configDock->setWidget(new TabWidget(this));
    Bottom_Dock_Chart->setFont(QFont("Microsoft YaHei UI", 8, 70));
    Bottom_Dock_Chart->setFeatures(QDockWidget::DockWidgetMovable);
    Bottom_Dock_Chart->setAllowedAreas(Qt::BottomDockWidgetArea);
    Bottom_Dock_Chart->setContentsMargins(0,0,0,0);
    Bottom_Dock_Chart->setWindowTitle(tr("TD_SC_Charts"));
    set_Bottom_Charts_back();
    //Bottom_Dock_Chart->hide();
    instrument =new QTreeWidgetItem(ui->treeWidget);
    instrument->setFont(0, QFont("Microsoft YaHei UI", 8, 70));
    instrument->setFont(1, QFont("Microsoft YaHei UI", 8, 70));
    instrument->setFont(2, QFont("Microsoft YaHei UI", 8, 70));
    instrument->setFont(3, QFont("Microsoft YaHei UI", 8, 70));
    instrument->setText(0,tr("仪器"));

    // 判断端口号是否存在
    QTreeWidgetItem* MLM =new QTreeWidgetItem(ui->treeWidget);
    MLM->setText(0,tr("MLM"));
    QTreeWidgetItem* Data =new QTreeWidgetItem(ui->treeWidget);
    Data->setText(0,tr("数据"));

    // 设置仪器和MLM以及数据的图标
    QIcon instrumentIcon;
    instrumentIcon.addPixmap(QPixmap(":/Image/instrument.ico"),QIcon::Normal);
    instrument->setIcon(0,instrumentIcon);
    itemT = new QTreeWidgetItem(instrument);
    itemTD = new QTreeWidgetItem(instrument);
    itemCTD_IM = new QTreeWidgetItem(instrument);
    
    itemTD->setHidden(true);
    itemT->setHidden(true);
    itemCTD_IM->setHidden(true);
    QIcon MLMIcon;
    MLMIcon.addPixmap(QPixmap(":/Image/single.ico"),QIcon::Normal);
    MLM->setIcon(0,MLMIcon);

    QIcon dataIcon;
    dataIcon.addPixmap(QPixmap(":/Image/access.ico"),QIcon::Normal);
    Data->setIcon(0,dataIcon);

    // 原则三个窗口，先左右后上下
    addDockWidget(Qt::LeftDockWidgetArea,navDock);
    addDockWidget(Qt::RightDockWidgetArea,configDock);
    addDockWidget(Qt::BottomDockWidgetArea,Bottom_Dock_Chart);
    setSampleStatus_not_sample(false);
    m_start_rotate->setEnabled(false);
}


void MainWindow::reciveTDSCComName(QString& portName)
{
    qDebug() << "itemTD" << itemTD;
    // 拔出串口，去除导航栏的item
    if (itemTD->parent())
    {
        itemTD->parent()->removeChild(itemTD);
    }
    ui->m_labelStatus->setText(tr("  串口拔出"));
    setSampleStatus_not_sample(false);
    m_start_rotate->setEnabled(false);

    int serialNumber = QSerialPortInfo::availablePorts().size();
    if (serialNumber == 2)
    {
        // 对应串口拔出
        if (deviceConfigTab->isHidden())
        {
            deviceConfigTab->show();
        }
        configDock->hide();
        if (!Bottom_Dock_Chart->isHidden())
        {
            Bottom_Dock_Chart->hide();
        }
        deviceChartsTSC->show();
    }
    // 对应定时器关闭
    m_Heart_timer->stop();

}

void MainWindow::reciveTSCComName(QString& portName)
{
    if (itemT->parent())
    {
        itemT->parent()->removeChild(itemT);
    }

    // 对应串口拔出，需要隐藏
    if (!deviceConfigTab->isHidden())
    {
        deviceConfigTab->hide();
    }
    configDock->show();
    if (!deviceChartsTSC->isHidden())
    {
        deviceChartsTSC->hide();
    }
    Bottom_Dock_Chart->show();

}

void MainWindow::setStopTimer()
{
    m_Heart_timer->stop();
}


void MainWindow::set_Bottom_Charts_back()
{
    QPen dpen;
    dpen.setWidth(2);
    dpen.setColor(QColor(252, 167, 54));
    m_chart = new QChart;

    m_dseries_Temperature = new QLineSeries;
    m_dseries_Temperature->setPen(dpen);
  //  m_dseries_Temperature->setColor(QColor(252, 167, 54));
    m_dseries_Temperature->setName("温度");  // 设置图例名字

    m_scatterSeries_T = new QScatterSeries();
    m_scatterSeries_T->setMarkerSize(8);
    m_scatterSeries_T->setColor(QColor(252, 167, 54));
    m_scatterSeries_T->setPointsVisible(true);


    m_dseries_Pressure = new QLineSeries;
    m_dseries_Pressure->setName("压力");

    m_scatterSeries_P = new QScatterSeries();
    m_scatterSeries_P->setMarkerSize(8);
    m_scatterSeries_P->setColor(QColor(128, 192, 128));

//    m_chart->setTitle("坐标图");
    m_chart->addSeries(m_dseries_Temperature);
    m_chart->addSeries(m_dseries_Pressure);
    m_chart->addSeries(m_scatterSeries_T);
    m_chart->addSeries(m_scatterSeries_P);

    QFont font_cutline;
    font_cutline.setFamily("微软雅黑");
    font_cutline.setPointSize(8);
    font_cutline.setBold(true);

    m_chart->legend()->markers().at(3)->setVisible(false);
    m_chart->legend()->markers().at(2)->setVisible(false);
    m_chart->legend()->setFont(QFont("Microsoft YaHei", 10, 70));

    // 设置X 轴坐标
    m_Time_daxisX = new QDateTimeAxis();
    m_Time_daxisX->colorChanged(QColor(32, 159, 223));
    m_Time_daxisX->setTitleText("Time");
    m_Time_daxisX->setTickCount(5);                // 设置X轴坐标网格数
    m_Time_daxisX->setFormat("h:mm:ss");
    m_Time_daxisX->setLabelsFont(QFont("Microsoft YaHei", 10, 70));

    QDateTime xMin,xMax;  // 设置时间坐标轴范围
    xMin=QDateTime::currentDateTime();
    xMax=xMin.addSecs(20);
    m_Time_daxisX->setRange(xMin,xMax);

    // 设置 Y 轴坐标
    daxisY_Temperature = new QValueAxis;
    QFont font_y_Temperature;
    font_y_Temperature.setFamily(QString("Microsoft YaHei"));
    font_y_Temperature.setPointSize(8);
    font_y_Temperature.setBold(true);
    daxisY_Temperature->setLabelsFont(font_y_Temperature);
    daxisY_Temperature->setTitleText("Temperature(°C)");
    daxisY_Temperature->setTitleBrush(QColor(252, 167, 54));
    daxisY_Temperature->setRange(0,10);
    daxisY_Temperature->setTickCount(5); // 设置Y轴坐标网格数
    daxisY_Temperature->setLabelFormat("%.4f");
    daxisY_Temperature->setLinePenColor(QColor(252, 167, 54));
    daxisY_Temperature->setLabelsColor(QColor(252, 167, 54));

    daxisY_Pressure = new QValueAxis;
    QFont font_y_Pressure;
    font_y_Pressure.setFamily(QString("Microsoft YaHei"));
    font_y_Pressure.setPointSize(8);
    font_y_Pressure.setBold(true);
    daxisY_Pressure->setLabelsFont(font_y_Pressure);
    daxisY_Pressure->setTitleText("pressure(dbar)");
    daxisY_Pressure->setTitleBrush(QColor(Qt::darkGreen));
    daxisY_Pressure->setRange(1,10);
    daxisY_Pressure->setTickCount(5);
    daxisY_Pressure->setLabelFormat("%.2f");
    daxisY_Pressure->setLinePenColor(QColor(Qt::darkGreen));
    daxisY_Pressure->setLabelsColor(QColor(Qt::darkGreen));

    daxisY_Pressure->setGridLineVisible(false);
    //m_scatterSeries_T->setVisible(false);  // 设置圆点可不可见

    m_chart->addAxis(m_Time_daxisX,Qt::AlignBottom);
    m_chart->addAxis(daxisY_Temperature,Qt::AlignLeft);
    m_chart->addAxis(daxisY_Pressure,Qt::AlignLeft);


    m_dseries_Temperature->attachAxis(m_Time_daxisX);
    m_dseries_Temperature->attachAxis(daxisY_Temperature);
    m_dseries_Pressure->attachAxis(m_Time_daxisX);
    m_dseries_Pressure->attachAxis(daxisY_Pressure);

    m_scatterSeries_T->attachAxis(m_Time_daxisX);
    m_scatterSeries_T->attachAxis(daxisY_Temperature);
   // scatterSeries->attachAxis(daxisY_Pressure);

    m_scatterSeries_P->attachAxis(m_Time_daxisX);
    m_scatterSeries_P->attachAxis(daxisY_Pressure);

    dchartView = new QChartView(m_chart,this);
    dchartView->setRenderHint(QPainter::Antialiasing);
    //dchartView->resize(1000,500);

    m_Bottom_TableWidget =new QTableWidget();
    // 设置列数
    m_Bottom_TableWidget->setColumnCount(3);
    // 设置行数
    m_Bottom_TableWidget->setRowCount(2);
    // 设置垂直表头不可见
    m_Bottom_TableWidget->verticalHeader()->setVisible(false);
    // 表头标题用QStringList来表示
    QStringList headerTest;
    //headerTest<<QStringLiteral("数值")<<QStringLiteral("最新取样值")<<QStringLiteral("单位");
    headerTest<<"功能"<<"最新取样值"<<"单位";
    m_Bottom_TableWidget->setHorizontalHeaderLabels(headerTest);
    m_Bottom_TableWidget->horizontalHeader()->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setEditTriggers(QTableWidget::NoEditTriggers);
    // 设置整行选中模式
    m_Bottom_TableWidget->setSelectionBehavior(QTableWidget::SelectRows);
    // 设置单选模式
    m_Bottom_TableWidget->setSelectionMode(QTableWidget::SingleSelection);
    // 设置最后一行自适应长度
    m_Bottom_TableWidget->horizontalHeader()->setStretchLastSection(true);

    QTableWidgetItem* item_Unit_Tem_Fun= new QTableWidgetItem("温度");
    item_Unit_Tem_Fun->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item_Unit_Tem_Fun->setForeground(QColor(252, 167, 54));
    item_Unit_Tem_Fun->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(0,0,item_Unit_Tem_Fun);

    QTableWidgetItem* item_Unit_Press_Fun= new QTableWidgetItem("压力");
    item_Unit_Press_Fun->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item_Unit_Press_Fun->setForeground(QColor(Qt::darkGreen));
    item_Unit_Press_Fun->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(1,0,item_Unit_Press_Fun);

    QTableWidgetItem* item_Unit_Tem= new QTableWidgetItem("°C");
    item_Unit_Tem->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item_Unit_Tem->setForeground(QColor(252, 167, 54));
    item_Unit_Tem->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(0,2,item_Unit_Tem);

    QTableWidgetItem* item_Unit_Press= new QTableWidgetItem("dbar");
    item_Unit_Press->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item_Unit_Press->setForeground(QColor(Qt::darkGreen));
    item_Unit_Press->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(1,2,item_Unit_Press);

 /*   m_Label_Sample_Save_Location = new QLabel();
    m_Label_Sample_Save_Location->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Label_Sample_Save_Location->setText("Capuring to C:Users");*/

    m_Label_Sample_Count = new QLabel();
    m_Label_Sample_Count->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Label_Sample_Count->setText(QString("Sample #:%1(captured)").arg(m_Sanple_count));

    m_Sample_Time = new QLabel();
    m_Sample_Time->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Sample_Time->setText(QString("Time: %1").arg(" "));

    /*m_Start_Tb = new QToolBar("Tool Bar");
    m_Start_Tb->setIconSize(QSize(16,16));
    m_Start_Tb->addAction(ui->signal_start);*/
    m_start_rotate->setFont(QFont("Microsoft YaHei", 10, 70));
    m_start_rotate->setText(tr("开启轮询"));
    m_start_rotate->setFixedSize(80, 30);
    // 垂直布局 上下结构
    m_vLayout = new QVBoxLayout();
    m_vLayout->addWidget(m_start_rotate);
    //m_vLayout->addWidget(m_Label_Sample_Save_Location);
    m_vLayout->addWidget(m_Label_Sample_Count);
    m_vLayout->addWidget(m_Sample_Time);
    m_vLayout->addWidget(m_Bottom_TableWidget);
    m_vLayout->setDirection(QBoxLayout::TopToBottom);
    //  m_vLayout->setDirection(QBoxLayout::RightToLeft);
    m_Right_Bottom = new QWidget();
    m_Right_Bottom->setLayout(m_vLayout);
    // m_Right_Bottom->resize(10,10);

    m_hLayout = new QHBoxLayout();
    // m_hLayout->addWidget(dchartView);
    m_hLayout->addWidget(dchartView);
    m_hLayout->addWidget(m_Right_Bottom);
    m_hLayout->setDirection(QBoxLayout::LeftToRight);
    // 比例
    m_hLayout->setStretchFactor(dchartView,5);
    m_hLayout->setStretchFactor(m_Right_Bottom,1);
    //ui->dockWidget_3->setWidget(dchartView);
    ui->dockWidgetBottomContents->setLayout(m_hLayout);
    // 开启循环
    connect(m_start_rotate,&QPushButton::clicked,this,[=](){
        if(m_Sample_Start_Flag_Time)
        {
            // read_config_file();

            QBox = true;
            if (!QBox)
            {
                // 提示用户没有找到文件
                QMessageBox::information(this, "提示信息", "没有配置文件", QMessageBox::Ok);
                return;
            }
            m_Sample_Start_Flag_Time = false;
            timerId = startTimer(1000);
            m_start_rotate->setText(tr("关闭轮询"));
            // 关闭其他按钮
            m_Heart_timer->stop();
            setSampleStatus_not_sample(false);
            //ui->signal_start->setIcon(QIcon(":/Image/signal_stop.png"));
        }
        else
        {
            killTimer(timerId);
            // QBox = false;
            m_Sample_Start_Flag_Time=true;
            m_start_rotate->setText(tr("开启轮询"));
            m_Heart_timer->start();
            setSampleStatus_not_sample(true);
            //ui->signal_start->setIcon(QIcon(":/Image/signal_start.png"));
        }

    });

}

void MainWindow::timerEvent(QTimerEvent *event)
{
#if 1
    if (event->timerId() == timerId) {
        emit send_Once_Sample();
    }
#endif
}

void MainWindow::HandleTypeData(Message_t stuMsg)
{
    if(stuMsg.deviceType=="5444")
    {
        //QByteArray trs =stuMsg.endWithType;
        switch (stuMsg.endWithType)
        {
        case 474947:
            this->HandleData(stuMsg.arrData,"5444");
            break;

        case 474256:
            this->HandleVoltageData(stuMsg.arrData,"5444");
            break;

        case 474946:
            this->HandlePlayData(stuMsg.arrData,"5444");
            break;

        case 535444:
        case 475444:
            this->HandleDeviceTimeData(stuMsg.arrData,"5444");
            break;

        case 475449:
            this->setSampleConfiguration(stuMsg.arrData,"5444");
            break;

        case 474354:
            this->setTemperatureCoefficient(stuMsg.arrData,"5444");
            break;

        case 474350:
            this->setPressureCoefficientData(stuMsg.arrData,"5444");
            break;

        case 534341:
            this->setTemperatureABData(stuMsg.arrData,"5444");
            break;

        case 534343:
            this->setTemperatureCDData(stuMsg.arrData,"5444");
            break;

        case 534342:
            this->set_Pressure_CoefficientAB_Data(stuMsg.arrData,"5444");
            break;

        case 534344:
            this->set_Pressure_CoefficientCD_Data(stuMsg.arrData,"5444");
            break;

        case 534654:
            this->set_Calibration_Time(stuMsg.arrData,"5444");
            break;

        case 475254:
            // this->set_Once_Sample_Data_Chart_back(stuMsg.arrData,"5444");
            setOnceSampleDataChartDebug(stuMsg.arrData, "5444");
            break;
        case 737461:
            setStartSample(stuMsg.arrData, "5444");
            break;

        case 46454:
            setProgressValue();
            break;
        }
    }

    // T-SC
    else if (stuMsg.deviceType == "5443")
    {
        if (configFlag)
        {
            // 替换 DockWidget
            deviceConfigTab = DeviceConfigTabInstance;
            configDock->hide();
            deviceConfigTab->show();
            addDockWidget(Qt::RightDockWidgetArea, deviceConfigTab);

            // TreeWidget添加
            int childIndex = instrument->indexOfChild(itemT);
            if (childIndex >= 0)
            {
                qDebug() << "包含子节点";
            }
            else
            {
                instrument->addChild(itemT);
            }
            itemT->setText(0, "T-SC");
            itemT->setHidden(false);
            connect(ui->treeWidget, &QTreeWidget::itemClicked, this, &MainWindow::getItem);

            itemT->setSelected(true);
           
            // 如果有 itemTD, 则让 itemTD 不选中
            if (instrument->indexOfChild(itemTD)>=0)
            {
                itemTD->setSelected(false);
            }

            instrument->setExpanded(true);

			// 替换打点
			deviceChartsTSC = DeviceChartsTSCInstance;
			deviceChartsTSC->m_start_rotate->setEnabled(true);
			Bottom_Dock_Chart->hide();
            deviceChartsTSC->show();
			addDockWidget(Qt::BottomDockWidgetArea, deviceChartsTSC);
        }
        // 开启 T-SC 定时器
        deviceConfigTab->m_timer_TSC->start(500);
       
    }

	// CTD-IM
	else if (stuMsg.deviceType == "435444")
	{
	// 替换 DockWidget
    //dockWidgetCTD_IM = DockWidgetCTDInstance;
	configDock->hide();
    dockWidgetCTD_IM->show();
	addDockWidget(Qt::RightDockWidgetArea, dockWidgetCTD_IM);

	// TreeWidget添加
	int childIndex = instrument->indexOfChild(itemCTD_IM);
	if (childIndex >= 0)
	{
		qDebug() << "包含子节点";
	}
	else
	{
		instrument->addChild(itemCTD_IM);
	}
    itemCTD_IM->setText(0, "CTD_IM");
    itemCTD_IM->setHidden(false);
	// connect(ui->treeWidget, &QTreeWidget::itemClicked, this, &MainWindow::getItem);

    itemCTD_IM->setSelected(true);

	// 如果有 itemTD, 则让 itemTD 不选中
	if (instrument->indexOfChild(itemTD) >= 0)
	{
		itemTD->setSelected(false);
	}
    // 如果有 itemT, 则让 itemT 不选中
    if (instrument->indexOfChild(itemT) >= 0)
    {
        itemT->setSelected(false);
    }
	instrument->setExpanded(true);


    // 替换打点
    dockWidgetCTD_IMCharts = DockWidgetCTD_IMChartsInstance;
    // deviceChartsTSC->m_start_rotate->setEnabled(true);
    Bottom_Dock_Chart->hide();
    dockWidgetCTD_IMCharts->show();
    addDockWidget(Qt::BottomDockWidgetArea, dockWidgetCTD_IMCharts);
	}
}

void MainWindow::getItem(QTreeWidgetItem* item, int column)
{
    qDebug() << "行数:"<<item->text(column);
    if (item->text(column) == "T-SC")
    {
        qDebug() << "T-SC的item";
        // 替换 DockWidget
        if (deviceConfigTab == NULL)
        {
            deviceConfigTab = DeviceConfigTabInstance;
        }
        if (!configDock->isHidden())
        {
            configDock->hide();
        }
        deviceConfigTab->show();
        addDockWidget(Qt::RightDockWidgetArea, deviceConfigTab);

        // TreeWidget添加
        itemT->setText(0, "T-SC");
        itemT->setHidden(false);

        itemT->setSelected(true);
        itemTD->setSelected(false);
        instrument->setExpanded(true);

        // 替换打点
        // deviceChartsTSC = new DeviceChartsTSC(this);
        if (deviceChartsTSC == NULL)
        {
            deviceChartsTSC = DeviceChartsTSCInstance;
        }
        if (!Bottom_Dock_Chart->isHidden())
        {
            Bottom_Dock_Chart->hide();
        }
        deviceChartsTSC->show();
        addDockWidget(Qt::BottomDockWidgetArea, deviceChartsTSC);
    }
    else if(item->text(column) == "TD-SC")
    {
        qDebug() << "TD-SC的item";
        configDock->show();
        // 替换 DockWidget
        if (!deviceConfigTab->isHidden())
        {
            deviceConfigTab->hide();
        }
        //deviceConfigTab = DeviceConfigTabInstance;
      
        addDockWidget(Qt::RightDockWidgetArea, configDock);

        // TreeWidget添加
        // itemT->setText(0, "TD-SC");
        // itemT->setHidden(false);
        itemTD->setHidden(false);

        itemT->setSelected(false);
        itemTD->setSelected(true);
        // configDock->show();
        instrument->setExpanded(true);
        if (!deviceChartsTSC->isHidden())
        {
            deviceChartsTSC->setHidden(true);
        }
   
        Bottom_Dock_Chart->show();
        addDockWidget(Qt::BottomDockWidgetArea, Bottom_Dock_Chart);

    }
}

void MainWindow::setOnceSampleDataChartDebug(QByteArray data, QByteArray flag)
{
    if (data.endsWith("475254") && flag == "5444")
    {
        auto iTemperature = data.mid(12, 6).toInt(nullptr, 16);
        auto iPressure = data.mid(18, 6).toInt(nullptr, 16);
        //        if(0xEE0000<iPressure)
        //        {
        //            iPressure = iPressure - 0xFFFFFF;
        //        }
        double dN = log(pow(2, 24) / iTemperature - 1);
        double dTemperature = 1 / (m_dT[0] + m_dT[1] * dN + m_dT[2] * pow(dN, 2) + m_dT[3] * pow(dN, 3)) - 273.15;

        double dK = iPressure / pow(2, 24);
        double sourcePressure = m_dP[0] + m_dP[1] * dK + m_dP[2] * pow(dK, 2) + m_dP[3] * pow(dK, 3);

        //double err = (DeviceConfig.at(DeviceId * 6 + 2) * (pow((dTemperature - DeviceConfig.at(DeviceId * 6 + 1)), 3))) + (DeviceConfig.at(DeviceId * 6 + 3) * (pow((dTemperature - DeviceConfig.at(DeviceId * 6 + 1)), 2))) + (DeviceConfig.at(DeviceId * 6 + 4) * (dTemperature - DeviceConfig.at(DeviceId * 6 + 1))) + DeviceConfig.at(DeviceId * 6 + 5);
        //double dPressure = sourcePressure - err;


        if ((dTemperature > -100 && dTemperature < 150) && (sourcePressure > -10 && sourcePressure < 1000))
        {
            if (m_bFirstSampling)
            {
                m_bFirstSampling = false;
                m_dMaxP = m_dMinP = sourcePressure;
                m_dMaxT = m_dMinT = dTemperature;
            }
            m_dMaxT = m_dMaxT < dTemperature ? dTemperature : m_dMaxT;
            m_dMinT = m_dMinT > dTemperature ? dTemperature : m_dMinT;
            m_dMaxP = m_dMaxP < sourcePressure ? sourcePressure : m_dMaxP;
            m_dMinP = m_dMinP > sourcePressure ? sourcePressure : m_dMinP;
            daxisY_Temperature->setRange(m_dMinT, m_dMaxT + 0.0009);
            daxisY_Pressure->setRange(m_dMinP, m_dMaxP + 0.0009);
        }
        QString currDatetime = QString("20" + data.left(12).insert(10, ':').insert(8, ':').insert(6, ' ').insert(4, '-').insert(2, '-'));
        if (m_currDatetime == currDatetime)
        {
            qDebug() << "哈哈，出错了,注意时间";
            return;
        }
        m_Label_Sample_Count->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Label_Sample_Count->setText(QString("Sample #:%1(captured)").arg(++m_Sanple_count));
        m_Sample_Time->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Sample_Time->setText(QString("Time: %1").arg(currDatetime));
        QDateTime currTime = QDateTime::fromString(currDatetime, "yyyy-MM-dd hh:mm:ss");
        if (m_isFirst_Simple)
        {
            // 再次更新坐标轴
            QDateTime xMin, xMax;  // 设置时间坐标轴范围
            xMin = currTime.toLocalTime();
            xMax = xMin.addSecs(20);
            m_Time_daxisX->setRange(xMin, xMax);
            m_isFirst_Simple = false;
        }

        QFont font_cutline;
        font_cutline.setFamily("微软雅黑");
        font_cutline.setPointSize(8);
        font_cutline.setBold(true);


        QDateTime t(currTime);
        //qDebug()<<"dTemperature:"<<dTemperature;
        m_dseries_Temperature->append(t.toMSecsSinceEpoch(), dTemperature);
        m_scatterSeries_T->append(t.toMSecsSinceEpoch(), dTemperature);
        m_dseries_Pressure->append(t.toMSecsSinceEpoch(), sourcePressure);
        m_scatterSeries_P->append(t.toMSecsSinceEpoch(), sourcePressure);
        // 设置表
        m_New_Value_Tem = new QTableWidgetItem(QString::number(dTemperature, 'f', 4));
        m_New_Value_Tem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        m_New_Value_Tem->setTextColor(QColor(252, 167, 54));
        m_New_Value_Tem->setFont(QFont("Microsoft YaHei", 10, 70));

        m_New_Value_Press = new QTableWidgetItem(QString::number(sourcePressure, 'f', 2));
        m_New_Value_Press->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        m_New_Value_Press->setTextColor(QColor(Qt::darkGreen));
        m_New_Value_Press->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Bottom_TableWidget->setItem(0, 1, m_New_Value_Tem);
        m_Bottom_TableWidget->setItem(1, 1, m_New_Value_Press);

        if (currTime > m_Time_daxisX->max())
        {
            QDateTime xMin;
            xMin = currTime.addSecs(qint64(-20));
            m_Time_daxisX->setRange(xMin, currTime);
        }
        m_currDatetime = currDatetime;
    }
}

void MainWindow::setStartSample(QByteArray data, QByteArray flag)
{
    if (flag == "5444")
    {
        uint iTotalSec = 0;
        if (ui->m_spinBox_Hour->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Hour->value() * 3600;
        }
        if (ui->m_spinBox_Minute->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Minute->value() * 60;
        }
        if (ui->m_spinBox_Second->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Second->value();
        }
        if (iTotalSec <= 0)
        {
            QMessageBox::information(this, "提示信息", "时间间隔小于0,请重新选择", QMessageBox::Ok);
            return;
        }
        if (iTotalSec >= 65535)
        {
            QMessageBox::information(this, "提示信息", "最大采样间隔18小时12分钟15秒", QMessageBox::Ok);
            return;
        }
        QByteArray arrTemp;
        arrTemp.push_back(iTotalSec / 256);
        arrTemp.push_back(iTotalSec % 256);
        QByteArray arrAA = ui->m_radio_LocalDateTime->isChecked() ? "00" : "01";   // 立即启动按钮点击则设置00 否则 01
        QByteArray arrEndDateTime=ui->m_dateTimeEdit_End->dateTime().toString("yyMMddhhmmss").toUtf8();   // 结束时间为用户设置的结束时间
        QByteArray arrStartDataTime=ui->m_radio_LocalDateTime->isChecked()?ui->m_labelDeviceTime->text().mid(2).remove('-').remove(':').remove(' ').toUtf8(): 
            ui->m_dateTimeEdit->dateTime().toString("yyMMddhhmmss").toUtf8();    // 立即按钮是否被点击了，若点击，开始时间设置500毫秒上来的RTC时间，否则设置用户设置的开始时间
        QByteArray sendData="EB9003"+ arrAA + arrStartDataTime + arrTemp.toHex().toUpper()+"FA"+arrEndDateTime;  // 组装指令
        confirmDevice->serial_TD.write(QByteArray::fromHex(sendData));  // 下发采样指令
        qDebug() << "sendData" << sendData;
    }
}

void MainWindow::setProgressValue()
{
    // 清空flash之后,设置进度条
    ui->m_proBar_Memory->setValue(0);
    // 然后下发LED是否启动指令
    arrLED = ui->m_radioButton_Led->isChecked() ? "01" : "00";
    confirmDevice->serial_TD.write(QByteArray::fromHex("EB9016" + arrLED + "000000000000000000000000000000"));
    qDebug() << "11111" << "EB9016" + arrLED + "000000000000000000000000000000";
}



void MainWindow::set_Once_Sample_Data_Chart_back(QByteArray data, QByteArray flag)
{


    if(data.endsWith("475254")&&flag=="5444")
    {
        auto iTemperature= data.mid(12,6).toInt(nullptr,16);
        auto iPressure= data.mid(18,6).toInt(nullptr,16);
//        if(0xEE0000<iPressure)
//        {
//            iPressure = iPressure - 0xFFFFFF;
//        }
        double dN=log(pow(2,24)/iTemperature-1);
        double dTemperature = 1 / (m_dT[0] + m_dT[1] * dN + m_dT[2]*pow(dN,2) + m_dT[3] * pow(dN,3)) -273.15;

        double dK = iPressure / pow(2,24);
        double sourcePressure = m_dP[0] + m_dP[1]*dK + m_dP[2] * pow(dK,2) + m_dP[3] * pow(dK,3);

        double err = (DeviceConfig.at(DeviceId * 6 + 2) * (pow((dTemperature - DeviceConfig.at(DeviceId * 6 + 1)), 3))) + (DeviceConfig.at(DeviceId * 6 + 3) * (pow((dTemperature - DeviceConfig.at(DeviceId * 6 + 1)), 2))) + (DeviceConfig.at(DeviceId * 6 + 4) * (dTemperature - DeviceConfig.at(DeviceId * 6 + 1))) + DeviceConfig.at(DeviceId * 6 + 5);
        //double err = (m_Pc[0]*(pow((m_vecTemperature[iNum]-Tm),2))) + (m_Pc[1]*(m_vecTemperature[iNum]-Tm)) + m_Pc[2] + m_Pc[3]/(m_vecTemperature[iNum]-Tm);
        double dPressure = sourcePressure - err;


        if((dTemperature>-100&&dTemperature<150)&&(dPressure>-10&&dPressure<1000))
        {
            if(m_bFirstSampling)
            {
                m_bFirstSampling = false;
                m_dMaxP = m_dMinP = dPressure;
                m_dMaxT = m_dMinT = dTemperature;
            }
            m_dMaxT = m_dMaxT < dTemperature ? dTemperature : m_dMaxT;
            m_dMinT = m_dMinT > dTemperature ? dTemperature : m_dMinT;
            m_dMaxP = m_dMaxP < dPressure ? dPressure : m_dMaxP;
            m_dMinP = m_dMinP > dPressure ? dPressure : m_dMinP;
            daxisY_Temperature->setRange(m_dMinT,m_dMaxT+0.0009);
            daxisY_Pressure->setRange(m_dMinP,m_dMaxP+0.0009);
        }
        // qDebug()<<"m_dMinT："<<m_dMinT<<"  m_dMaxT："<<m_dMaxT<<" m_dMinP："<<m_dMinP<<" m_dMaxP："<<m_dMaxP;
        QString currDatetime  = QString("20" + data.left(12).insert(10, ':').insert(8, ':').insert(6, ' ').insert(4, '-').insert(2, '-'));
        // qDebug()<<"currDatetime"<<currDatetime<<"m_currDatetime"<<m_currDatetime;
        if(m_currDatetime ==currDatetime)
        {
            qDebug()<<"哈哈，出错了,注意时间";
            return;
        }
        m_Label_Sample_Count->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Label_Sample_Count->setText(QString("Sample #:%1(captured)").arg(++m_Sanple_count));
        m_Sample_Time->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Sample_Time->setText(QString("Time: %1").arg(currDatetime));
        QDateTime currTime = QDateTime::fromString(currDatetime,"yyyy-MM-dd hh:mm:ss");
        if(m_isFirst_Simple)
        {
            //    再次更新坐标轴
            QDateTime xMin,xMax;  // 设置时间坐标轴范围
            xMin=currTime.toLocalTime();
            xMax=xMin.addSecs(20);
            m_Time_daxisX->setRange(xMin,xMax);
            m_isFirst_Simple=false;
        }

        QFont font_cutline;
        font_cutline.setFamily("微软雅黑");
        font_cutline.setPointSize(8);
        font_cutline.setBold(true);


        QDateTime t(currTime);
        //qDebug()<<"dTemperature:"<<dTemperature;
        m_dseries_Temperature->append(t.toMSecsSinceEpoch(),dTemperature);
        m_scatterSeries_T->append(t.toMSecsSinceEpoch(),dTemperature);
        m_dseries_Pressure->append(t.toMSecsSinceEpoch(),dPressure);
        m_scatterSeries_P->append(t.toMSecsSinceEpoch(),dPressure);
        // 设置表
        m_New_Value_Tem = new QTableWidgetItem(QString::number(dTemperature,'f',4));
        m_New_Value_Tem->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        m_New_Value_Tem->setTextColor(QColor(252, 167, 54));
        m_New_Value_Tem->setFont(QFont("Microsoft YaHei", 10, 70));

        m_New_Value_Press = new QTableWidgetItem(QString::number(dPressure,'f',2));
        m_New_Value_Press->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        m_New_Value_Press->setTextColor(QColor(Qt::darkGreen));
        m_New_Value_Press->setFont(QFont("Microsoft YaHei", 10, 70));
        m_Bottom_TableWidget->setItem(0,1,m_New_Value_Tem);
        m_Bottom_TableWidget->setItem(1,1,m_New_Value_Press);

        if(currTime > m_Time_daxisX->max())
        {
            QDateTime xMin;
            xMin = currTime.addSecs(qint64(-20));
            m_Time_daxisX->setRange(xMin,currTime);
        }
        m_currDatetime=currDatetime;
    }
}






QString MainWindow::getHexToStr(QString hexStr)
{
    QString targetStr = "";
    // trimmed() 仅去除首尾空格
    hexStr = hexStr.trimmed();
    // simplified() 可去除中间空格
    hexStr = hexStr.simplified();
    // QStringList strList = hexStr.split(" ");
    for(size_t i=0;i<hexStr.length();i+=2)
    {
        QString part=hexStr.mid(i,2);
        if(!part.isEmpty())
        {
            char ch=part.toInt(nullptr,16)&0xFF;
            targetStr+=ch;
        }
    }
    return targetStr;
}




// 确定型号
void MainWindow::HandleData(QString data, QString flag)
{
    qDebug() << "data===" << data;
    // 型号 TD 系列
    if(flag=="5444")
    {
        if (!deviceConfigTab->isHidden())
        {
            deviceConfigTab->hide();
        }
        if (!deviceChartsTSC->isHidden())
        {
            deviceChartsTSC->hide();
        }
        Bottom_Dock_Chart->show();
        addDockWidget(Qt::BottomDockWidgetArea, Bottom_Dock_Chart);
        itemT->setSelected(false);
        itemTD->setSelected(true);

        // 型号
        if(data.mid(0,4)=="5444")
		{
			ui->label_type->setText("OceanPlot-TD");

			int childIndex = instrument->indexOfChild(itemTD);
			if (childIndex >= 0)
			{
				qDebug() << "包含子节点";
			}
			else {
				qDebug() << "不包含子节点";
				instrument->addChild(itemTD);
			}
			// QString TDitem = "TD-SC   " + data.mid(26, 6);

			itemTD->setText(0, "TD-SC");
			itemTD->setHidden(false);
			//instrument->setExpanded(true);
			itemTD->setSelected(true);
			configDock->show();
			instrument->setExpanded(true);

		}

        // 硬件版本信息
        QByteArray HardArr =  data.mid(12,6).toUtf8();
        //qDebug()<<"HardArr.data()="<<QByteArray::fromHex(HardArr.data());
        QByteArray aimArr;
        for(int i=0;i<6;i+=2)
        {
            char c1=char(hexCharToInt(HardArr[i])*16+hexCharToInt(HardArr[i+1]));
            aimArr.append(c1);
        }
        aimArr.insert(1,".").insert(3,".");
        ui->m_labelHardWare->setText(aimArr);

        QByteArray SoftwareVersionArr =  data.mid(18,8).toUtf8();
        QByteArray SoftArr;
        for(int i=0;i<8;i+=2)
        {
            char c1=char(hexCharToInt(SoftwareVersionArr[i])*16+hexCharToInt(SoftwareVersionArr[i+1]));
            SoftArr.append(c1);
        }
        SoftArr.insert(1,".").insert(3,".").insert(5,".");
        ui->m_labelSoftwareVersion->setText(SoftArr);

        m_Serial=data.mid(26,6).remove(QRegExp("^[0]*"));
        // 序列号,去除任意数量的零
        //ui->m_labelSerial->setText(data.mid(26,6).remove(QRegExp("^[0]*")));
        ui->m_labelSerial->setText(data.mid(26,6));
    }
    // 找到设备开启定时器
    m_Heart_timer->start(500);
}

// 电池电量信息
void MainWindow::HandleVoltageData(QString data, QString flag)
{
    QString result = getHexToStr(data);
    if(data.contains("474256")&&flag=="5444")
    {
        bool ok;
        // 16转10
        double value = (double)(data.mid(0,4).toInt(&ok,16))/128;
        QString str=QString::number(value,'f',2).append("V");
        ui->m_labelVoltage->setText(str);
        data.mid(4,2)=="00"?ui->m_radioButton_Led->setChecked(false):ui->m_radioButton_Led->setChecked(true);

        QString CalibrationTime="20"+QString("%1").arg(data.mid(6,2).toInt(nullptr,16),2,10,QChar('0'))+"-"+QString("%1").arg(data.mid(8,2).toInt(nullptr,16),2,10,QChar('0'))+"-"+QString("%1").arg(data.mid(10,2).toInt(nullptr,16),2,10,QChar('0'))
                +" "+QString("%1").arg(data.mid(12,2).toInt(nullptr,16),2,10,QChar('0'))+":"+QString("%1").arg(data.mid(14,2).toInt(nullptr,16),2,10,QChar('0'))+":"+QString("%1").arg(data.mid(16,2).toInt(nullptr,16),2,10,QChar('0'));

        ui->m_groupBox_CalibrationDate->setTitle("校准日期:"+CalibrationTime);
    }
}

void MainWindow::HandlePlayData(QString data, QString flag)
{

    // 设置时间
    LocalDateTime = "20" + data.mid(10, 2) + "-" + data.mid(12, 2) + "-" + data.mid(14, 2) + " " + data.mid(16, 2) + ":" + data.mid(18, 2) + ":" + data.mid(20, 2);
    ui->m_labelDeviceTime->setText(LocalDateTime);

    if(data.contains("474946")&&flag=="5444")
    {
        label_Start_Status = data.mid(0,4);
        if(label_Start_Status=="0100")
        {
            m_Start_Simple = false;
            setSampleStatus_01(false);
            ui->m_pushButton_StartSample->setEnabled(true);
            ui->m_labelStatus->setText(tr(" 已启用,等待开始"));
            ui->m_pushButton_StartSample->setText(" 停止");
        }
        else if(label_Start_Status=="0200")
        {
            m_Start_Simple = false;
            ui->m_labelStatus->setText(tr(" 采样中"));
            setSampleStatus_02(false);
            ui->m_pushButton_StartSample->setEnabled(true);
            ui->m_pushButton_StartSample->setText(" 停止");
        }
        else if(label_Start_Status=="0401")
        {
            m_Start_Simple = true;
            ui->m_labelStatus->setText(tr(" 按计划采样完毕"));
			setSampleStatus_Flag_03(true);
            ui->m_pushButton_StartSample->setEnabled(true);
            ui->m_pushButton_StartSample->setText("启用");
        }

        else if(label_Start_Status=="0402")
        {
            m_Start_Simple = true;
            setSampleStatus_Flag_03(true);
            ui->m_pushButton_StartSample->setEnabled(true);
            ui->m_labelStatus->setText(tr(" 用户终止"));
            ui->m_pushButton_StartSample->setText("启用");
        }

        else if(label_Start_Status=="0403")
        {
            ui->m_labelStatus->setText(tr(" flash已存满"));
        }
        m_iPageQuantity = data.mid(4,6).toUInt(nullptr,16);
        ui->m_proBar_Memory->setValue(100 * m_iPageQuantity / 524288);
    }
}
#if 1
void MainWindow::setSampleStatus_01(bool flag)
{
    ui->m_Button_SyncLocalTime->setEnabled(flag);
    ui->m_dateTimeEdit->setEnabled(flag);
    ui->m_dateTimeEdit_End->setEnabled(flag);
    ui->m_radio_LocalDateTime->setEnabled(flag);
    ui->m_radioButton_Led->setEnabled(flag);
    ui->m_pbn_Save_Config->setEnabled(flag);
    ui->m_Use_Last_Config->setEnabled(flag);

    ui->m_spinBox_Hour->setEnabled(flag);
    ui->m_spinBox_Minute->setEnabled(flag);
    ui->m_spinBox_Second->setEnabled(flag);
    ui->m_radioButton_Hour->setEnabled(flag);
    ui->m_radioButton_Minute->setEnabled(flag);
    ui->m_radioButton_Second->setEnabled(flag);

    ui->m_pbn_DownLoad->setEnabled(flag);
    ui->m_Ptn_SaveCoefficient->setEnabled(flag);
    ui->m_Calibration_Coefficient->setEnabled(flag);
    m_start_rotate->setEnabled(flag);

    

}


void MainWindow::setSampleStatus_02(bool flag)
{
    ui->m_Button_SyncLocalTime->setEnabled(flag);
    ui->m_dateTimeEdit->setEnabled(flag);
    ui->m_dateTimeEdit_End->setEnabled(flag);
    ui->m_radio_LocalDateTime->setEnabled(flag);
    ui->m_radioButton_Led->setEnabled(flag);
    ui->m_pbn_Save_Config->setEnabled(flag);
    ui->m_Use_Last_Config->setEnabled(flag);

    ui->m_spinBox_Hour->setEnabled(flag);
    ui->m_spinBox_Minute->setEnabled(flag);
    ui->m_spinBox_Second->setEnabled(flag);
    ui->m_radioButton_Hour->setEnabled(flag);
    ui->m_radioButton_Minute->setEnabled(flag);
    ui->m_radioButton_Second->setEnabled(flag);

    ui->m_pbn_DownLoad->setEnabled(flag);
    ui->m_Ptn_SaveCoefficient->setEnabled(flag);
    ui->m_Calibration_Coefficient->setEnabled(flag);
    m_start_rotate->setEnabled(flag);
}

void MainWindow::setSampleStatus_Flag_03(bool flag)
{
    ui->m_Button_SyncLocalTime->setEnabled(flag);
    //ui->m_dateTimeEdit->setEnabled(flag);
    ui->m_dateTimeEdit_End->setEnabled(flag);
    ui->m_radio_LocalDateTime->setEnabled(flag);
    ui->m_radioButton_Led->setEnabled(flag);
    ui->m_pbn_Save_Config->setEnabled(flag);
    ui->m_Use_Last_Config->setEnabled(flag);

    ui->m_spinBox_Second->setEnabled(flag);
    ui->m_radioButton_Hour->setEnabled(flag);
    ui->m_radioButton_Minute->setEnabled(flag);
    ui->m_radioButton_Second->setEnabled(flag);

    ui->m_pbn_DownLoad->setEnabled(flag);
    ui->m_Ptn_SaveCoefficient->setEnabled(flag);
    ui->m_Calibration_Coefficient->setEnabled(flag);
    m_start_rotate->setEnabled(flag);
}

void MainWindow::setSampleStatus_not_sample(bool flag)
{
    ui->m_Button_SyncLocalTime->setEnabled(flag);
    ui->m_dateTimeEdit->setEnabled(flag);
    ui->m_dateTimeEdit_End->setEnabled(flag);
    ui->m_radio_LocalDateTime->setEnabled(flag);
    ui->m_radioButton_Led->setEnabled(flag);
    ui->m_pbn_Save_Config->setEnabled(flag);
    ui->m_Use_Last_Config->setEnabled(flag);

    ui->m_spinBox_Hour->setEnabled(flag);
    ui->m_spinBox_Minute->setEnabled(flag);
    ui->m_spinBox_Second->setEnabled(flag);
    ui->m_radioButton_Hour->setEnabled(flag);
    ui->m_radioButton_Minute->setEnabled(flag);
    ui->m_radioButton_Second->setEnabled(flag);
    ui->m_pbn_DownLoad->setEnabled(flag);
    ui->m_Ptn_SaveCoefficient->setEnabled(flag);
    ui->m_Calibration_Coefficient->setEnabled(flag);
    ui->m_pushButton_StartSample->setEnabled(flag);
}

#endif
void MainWindow::HandleDeviceTimeData(QString data, QString flag)
{
    if((data.contains("475444")||data.contains("535444")) &&flag=="5444")
    {
        LocalDateTime="20"+data.mid(0,2)+"-"+data.mid(2,2)+"-"+data.mid(4,2)+" "+data.mid(6,2)+":"+data.mid(8,2)+":"+data.mid(10,2);
        ui->m_labelDeviceTime->setText(LocalDateTime);
    }

}

void MainWindow::syncStartDateTime(QString data, QString flag)
{
    if((data.contains("475444")) &&flag=="5444")
    {
        QString restTime="20"+data.mid(0,2)+"-"+data.mid(2,2)+"-"+data.mid(4,2)+" "+data.mid(6,2)+":"+data.mid(8,2)+":"+data.mid(10,2);
        //ui->m_labelDeviceTime->setText("20"+data.mid(0,2)+"-"+data.mid(2,2)+"-"+data.mid(4,2)+" "+data.mid(6,2)+":"+data.mid(8,2)+":"+data.mid(10,2));
    }
}

void MainWindow::setSampleConfiguration(QString data, QString flag)
{
    if(data.contains("475449")&&flag=="5444")
    {
        QString startDate="20"+data.mid(2,2)+"-"+data.mid(4,2)+"-"+data.mid(6,2)+" "+data.mid(8,2)+":"+data.mid(10,2)+":"+data.mid(12,2);
        QDateTime time=QDateTime::fromString(startDate,"yyyy-MM-dd hh:mm:ss");
        ui->m_dateTimeEdit->setDateTime(time);
        QString endDate="20"+data.mid(14,2)+"-"+data.mid(16,2)+"-"+data.mid(18,2)+" "+data.mid(20,2)+":"+data.mid(22,2)+":"+data.mid(24,2);
        time=QDateTime::fromString(endDate,"yyyy-MM-dd hh:mm:ss");
        ui->m_dateTimeEdit_End->setDateTime(time);
        sampleInterval=data.mid(26,4).toInt(nullptr,16);
        int iSec=sampleInterval%60;
        int iHour=sampleInterval/3600;
        int iMin=sampleInterval%3600/60;
        if(iHour>0)
        {
            ui->m_radioButton_Hour->setChecked(true);
            ui->m_spinBox_Hour->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(true);
            ui->m_spinBox_Second->setEnabled(true);
        }
        else if(iMin>0)
        {
            ui->m_radioButton_Minute->setChecked(true);
            ui->m_spinBox_Second->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(true);
            ui->m_spinBox_Hour->setEnabled(false);
        }
        else if(iSec>0)
        {
            ui->m_radioButton_Second->setChecked(true);
            ui->m_spinBox_Second->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(false);
            ui->m_spinBox_Hour->setEnabled(false);

        }
        ui->m_spinBox_Hour->setValue(iHour);
        ui->m_spinBox_Minute->setValue(iMin);
        ui->m_spinBox_Second->setValue(iSec);

        data.mid(0,2)=="00"?ui->m_radio_LocalDateTime->setChecked(true):ui->m_radio_LocalDateTime->setChecked(false);

        m_bIM="00"==data.mid(0,2) ? true:false;
    }
}

void MainWindow::setTemperatureCoefficient(QString data, QString flag)
{

    if(data.contains("474354")&&flag=="5444")
    {
        QByteArray bytArrA=data.mid(0,16).toUtf8();
        char cA[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrA[i])*16+hexCharToInt(bytArrA[i+1]));
            cA[7-i/2]=c1;
        }
        memcpy(&m_dT[0],cA,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dT[0],0,'R',15)));

        QByteArray bytArrB=data.mid(16,16).toUtf8();
        char cB[9];   
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrB[i])*16+hexCharToInt(bytArrB[i+1]));
            cB[7-i/2]=c1;
        }
        memcpy(&m_dT[1],cB,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dT[1],0,'R',15)));


        QByteArray bytArrC=data.mid(32,16).toUtf8();
        char cC[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrC[i])*16+hexCharToInt(bytArrC[i+1]));
            cC[7-i/2]=c1;
        }
        memcpy(&m_dT[2],cC,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dT[2],0,'R',15)));

        QByteArray bytArrD=data.mid(48,16).toUtf8();
        char cD[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrD[i])*16+hexCharToInt(bytArrD[i+1]));
            cD[7-i/2]=c1;
        }
        memcpy(&m_dT[3],cD,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dT[3],0,'R',15)));
    }
}
int MainWindow::hexCharToInt(char cHex)
{
    int aAscllCode=int(cHex);
    int nResult=-1;
    // 0-9
    if(47<aAscllCode&&aAscllCode<58)
    {
        nResult=aAscllCode-48;
    }
    // A-F
    else if(64<aAscllCode&&aAscllCode<71)
    {
        nResult=aAscllCode-55;
    }
    // a-f
    else if(96<aAscllCode&&aAscllCode<103)
    {
        nResult=aAscllCode-87;
    }
    return nResult;
}

void MainWindow::set_Calibration_Coefficient_Temperature_Table()
{
    ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dT[0],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dT[1],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dT[2],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dT[3],0,'R',15)));
}

void MainWindow::set_Calibration_Coefficient_Pressure_Table()
{
    ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dP[0],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dP[1],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dP[2],0,'R',15)));
    ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dP[3],0,'R',15)));
}



void MainWindow::setPressureCoefficientData(QString data, QString flag)
{
    if(data.contains("474350")&&flag=="5444")
    {
        QByteArray bytArrA=data.mid(0,16).toUtf8();
        char cA[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrA[i])*16+hexCharToInt(bytArrA[i+1]));
            cA[7-i/2]=c1;
        }
        memcpy(&m_dP[0],cA,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dP[0],0,'R',15)));

        QByteArray bytArrB=data.mid(16,16).toUtf8();
        char cB[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrB[i])*16+hexCharToInt(bytArrB[i+1]));
            cB[7-i/2]=c1;
        }
        memcpy(&m_dP[1],cB,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dP[1],0,'R',15)));


        QByteArray bytArrC=data.mid(32,16).toUtf8();
        char cC[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrC[i])*16+hexCharToInt(bytArrC[i+1]));
            cC[7-i/2]=c1;
        }
        memcpy(&m_dP[2],cC,sizeof(double));
        //ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dP[2],0,'R',15)));


        QByteArray bytArrD=data.mid(48,16).toUtf8();
        char cD[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrD[i])*16+hexCharToInt(bytArrD[i+1]));
            cD[7-i/2]=c1;
        }
        memcpy(&m_dP[3],cD,sizeof(double));
        ui->m_combomBox_Coefficient->setCurrentIndex(0);
    }

    if(ui->m_combomBox_Coefficient->currentIndex()==0)
    {
        set_Calibration_Coefficient_Temperature_Table();
    }
    if(ui->m_combomBox_Coefficient->currentIndex()==1)
    {
        set_Calibration_Coefficient_Pressure_Table();
    }

    if(m_index_CombomBox==0)
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(0);
        set_Calibration_Coefficient_Temperature_Table();
    }
    if(m_index_CombomBox==1)
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(1);
        set_Calibration_Coefficient_Pressure_Table();
    }
}

void MainWindow::setTemperatureABData(QByteArray data,QByteArray flag)
{

    if(data.contains("534341")&& flag=="5444")
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(0);
        QByteArray bytArrA=data.mid(0,16);
        char cA[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrA[i])*16+hexCharToInt(bytArrA[i+1]));
            cA[7-i/2]=c1;
        }
        memcpy(&m_dT[0],cA,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dT[0],0,'R',15)));

        QByteArray bytArrB=data.mid(16,16);
        char cB[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrB[i])*16+hexCharToInt(bytArrB[i+1]));
            cB[7-i/2]=c1;
        }
        memcpy(&m_dT[1],cB,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dT[1],0,'R',15)));

        //qDebug()<<"arrSend="<<arrSend.toHex();
        QByteArray arrDataCD;
        QByteArray arrSendCD;
        double dT2 =ui->m_tableWidget_CalibrationT->item(2,1)->text().toDouble();
        double dT3 =ui->m_tableWidget_CalibrationT->item(3,1)->text().toDouble();

        arrDataCD.resize(2*sizeof(double));
        memcpy(arrDataCD.data(),&dT3,sizeof(double));
        memcpy(arrDataCD.data()+sizeof(double),&dT2,sizeof(double));
        for(auto byte:arrDataCD)
        {
            arrSendCD.push_front(byte);
        }
        emit sendTemperatureCD(arrSendCD.toHex());
    }

}

void MainWindow::setTemperatureCDData(QByteArray data, QByteArray flag)
{
    if(data.contains("534343")&& flag=="5444")
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(0);
        QByteArray bytArrC=data.mid(0,16);
        char cC[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrC[i])*16+hexCharToInt(bytArrC[i+1]));
            cC[7-i/2]=c1;
        }
        memcpy(&m_dT[2],cC,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dT[2],0,'R',15)));


        QByteArray bytArrD=data.mid(16,16);
        char cD[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrD[i])*16+hexCharToInt(bytArrD[i+1]));
            cD[7-i/2]=c1;
        }
        memcpy(&m_dT[3],cD,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dT[3],0,'R',15)));

        QByteArray arrCurTime = QDateTime::currentDateTime().toString("yyMMddhhmmss").toUtf8();
        QString strCurTime = QString("%1%2%3%4%5%6").arg(arrCurTime.mid(0, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(2, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(4, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(6, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(8, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(10, 2).toUInt(), 2, 16, QChar('0'));
        emit send_Calibration_Time(strCurTime.toUtf8());
    }
}

void MainWindow::set_Pressure_CoefficientAB_Data(QByteArray data, QByteArray flag)
{
    if(data.contains("534342")&& flag=="5444")
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(1);
        QByteArray bytArrA=data.mid(0,16);
        char cA[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrA[i])*16+hexCharToInt(bytArrA[i+1]));
            cA[7-i/2]=c1;
        }
        memcpy(&m_dP[0],cA,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dP[0],0,'R',15)));

        QByteArray bytArrB=data.mid(16,16);
        char cB[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrB[i])*16+hexCharToInt(bytArrB[i+1]));
            cB[7-i/2]=c1;
        }
        memcpy(&m_dP[1],cB,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dP[1],0,'R',15)));

        QByteArray arrDataCD;
        QByteArray arrSendCD;
        double dP2 =ui->m_tableWidget_CalibrationT->item(2,1)->text().toDouble();
        double dP3 =ui->m_tableWidget_CalibrationT->item(3,1)->text().toDouble();

        arrDataCD.resize(2*sizeof(double));
        memcpy(arrDataCD.data(),&dP3,sizeof(double));
        memcpy(arrDataCD.data()+sizeof(double),&dP2,sizeof(double));
        for(auto byte:arrDataCD)
        {
            arrSendCD.push_front(byte);
        }
        emit send_Pressure_CoefficientCD(arrSendCD.toHex());
    }
}

void MainWindow::set_Pressure_CoefficientCD_Data(QByteArray data, QByteArray flag)
{
    if(data.contains("534344")&& flag=="5444")
    {
        ui->m_combomBox_Coefficient->setCurrentIndex(1);
        QByteArray bytArrA=data.mid(0,16);
        char cA[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrA[i])*16+hexCharToInt(bytArrA[i+1]));
            cA[7-i/2]=c1;
        }
        memcpy(&m_dP[2],cA,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dP[2],0,'R',15)));

        QByteArray bytArrB=data.mid(16,16);
        char cB[9];
        for(int i=0;i<16;i+=2)
        {
            char c1=char(hexCharToInt(bytArrB[i])*16+hexCharToInt(bytArrB[i+1]));
            cB[7-i/2]=c1;
        }
        memcpy(&m_dP[3],cB,sizeof(double));
        ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dP[3],0,'R',15)));

        QByteArray arrCurTime = QDateTime::currentDateTime().toString("yyMMddhhmmss").toUtf8();
        QString strCurTime = QString("%1%2%3%4%5%6").arg(arrCurTime.mid(0, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(2, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(4, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(6, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(8, 2).toUInt(), 2, 16, QChar('0')).arg(arrCurTime.mid(10, 2).toUInt(), 2, 16, QChar('0'));
        emit send_Calibration_Time(strCurTime.toUtf8());
    }



}

void MainWindow::set_Calibration_Time(QByteArray data, QByteArray flag)
{
    if(data.contains("534654")&&flag==("5444"))
    {

        QString CalibrationTime = "20" + QString("%1").arg(data.mid(2, 2).toInt(nullptr, 16), 2, 10, QChar('0')) + "-" + QString("%1").arg(data.mid(4, 2).toInt(nullptr, 16), 2, 10, QChar('0')) + "-" + QString("%1").arg(data.mid(6, 2).toInt(nullptr, 16), 2, 10, QChar('0'))
            + " " + QString("%1").arg(data.mid(8, 2).toInt(nullptr, 16), 2, 10, QChar('0')) + ":" + QString("%1").arg(data.mid(10, 2).toInt(nullptr, 16), 2, 10, QChar('0')) + ":" + QString("%1").arg(data.mid(12, 2).toInt(nullptr, 16), 2, 10, QChar('0'));
        ui->m_groupBox_CalibrationDate->setTitle("校准日期:" + CalibrationTime);
    }
}

void MainWindow::setChannel()
{
    ui->m_groupBoxChannel->setMaximumWidth(500);
    ui->m_groupBoxChannel->setMaximumHeight(600);
    ui->m_TableChannel->setColumnWidth(0,120);
}

void MainWindow::on_m_Button_SyncLocalTime_clicked()
{
    // 获取系统时间,显示到当前ui, 并 设置 设备时间
    QDateTime dateTime = QDateTime::currentDateTime();
    QString strDateTime = dateTime.toString("yyMMddhhmmss");
    QString setDeviceTime = "EB9002" + strDateTime + "00000000000000000000";
    confirmDevice->serial_TD.write(QByteArray::fromHex(setDeviceTime.toLatin1()));
}


void MainWindow::on_m_radio_LocalDateTime_clicked(bool checked)
{
    if(checked)
    {
        QDateTime time;
        time=QDateTime::fromString(LocalDateTime,"yyyy-MM-dd hh:mm:ss");
        ui->m_dateTimeEdit->setDateTime(time);
        ui->m_dateTimeEdit->setEnabled(false);
    }
    else
    {
        ui->m_dateTimeEdit->setEnabled(true);
    }
}

void MainWindow::on_m_radioButton_Minute_clicked(bool checked)
{
    if(checked)
    {
        ui->m_spinBox_Hour->setEnabled(!checked);
    }
    ui->m_spinBox_Minute->setEnabled(checked);
    ui->m_spinBox_Second->setEnabled(checked);

}

void MainWindow::on_m_radioButton_Hour_clicked(bool checked)
{
    if(checked)
    {
        ui->m_spinBox_Hour->setEnabled(checked);
        ui->m_spinBox_Minute->setEnabled(checked);
        ui->m_spinBox_Second->setEnabled(checked);
    }
}

void MainWindow::on_m_radioButton_Second_clicked(bool checked)
{
    if(checked)
    {
        ui->m_spinBox_Hour->setEnabled(!checked);
        ui->m_spinBox_Minute->setEnabled(!checked);
    }
}

void MainWindow::on_m_combomBox_Coefficient_currentIndexChanged(int index)
{
    Q_UNUSED(index);
    if(ui->m_combomBox_Coefficient->currentIndex()==0)
    {
        ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dT[0],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dT[1],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dT[2],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dT[3],0,'R',15)));
    }
    if(ui->m_combomBox_Coefficient->currentIndex()==1)
    {
        ui->m_tableWidget_CalibrationT->setItem(0,1,new QTableWidgetItem(QString("%1").arg(m_dP[0],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(1,1,new QTableWidgetItem(QString("%1").arg(m_dP[1],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(2,1,new QTableWidgetItem(QString("%1").arg(m_dP[2],0,'R',15)));
        ui->m_tableWidget_CalibrationT->setItem(3,1,new QTableWidgetItem(QString("%1").arg(m_dP[3],0,'R',15)));
    }
}


void MainWindow::on_m_Ptn_SaveCoefficient_clicked()
{
    //T coefficient
    if(ui->m_combomBox_Coefficient->currentIndex()==0)
    {
        QByteArray arrData;
        QByteArray arrSend;
        double dT0 =ui->m_tableWidget_CalibrationT->item(0,1)->text().toDouble();
        double dT1 =ui->m_tableWidget_CalibrationT->item(1,1)->text().toDouble();

        arrData.resize(2*sizeof(double));
        memcpy(arrData.data(),&dT1,sizeof(double));
        memcpy(arrData.data()+sizeof(double),&dT0,sizeof(double));
        for(auto byte:arrData)
        {
            arrSend.push_front(byte);
        }

        //qDebug()<<"arrSend="<<arrSend.toHex();
        QByteArray arrDataCD;
        QByteArray arrSendCD;
        double dT2 =ui->m_tableWidget_CalibrationT->item(2,1)->text().toDouble();
        double dT3 =ui->m_tableWidget_CalibrationT->item(3,1)->text().toDouble();

        arrDataCD.resize(2*sizeof(double));
        memcpy(arrDataCD.data(),&dT3,sizeof(double));
        memcpy(arrDataCD.data()+sizeof(double),&dT2,sizeof(double));
        for(auto byte:arrDataCD)
        {
            arrSendCD.push_front(byte);
        }
        emit sendTemperatureCoefficient(arrSend.toHex(),arrSendCD.toHex());
    }

    // 压强
    //T coefficient
    if(ui->m_combomBox_Coefficient->currentIndex()==1)
    {
        QByteArray arrData;
        QByteArray arrSend;
        double dP0 =ui->m_tableWidget_CalibrationT->item(0,1)->text().toDouble();
        double dP1 =ui->m_tableWidget_CalibrationT->item(1,1)->text().toDouble();
        arrData.resize(2*sizeof(double));
        memcpy(arrData.data(),&dP1,sizeof(double));
        memcpy(arrData.data()+sizeof(double),&dP0,sizeof(double));
        for(auto byte:arrData)
        {
            arrSend.push_front(byte);
        }
        emit sendPressureCoefficientAB(arrSend.toHex());
    }

}   

void MainWindow::on_m_Calibration_Coefficient_clicked()
{
    emit send_Get_Calibration_Coefficient();
    m_index_CombomBox=ui->m_combomBox_Coefficient->currentIndex();
}


void MainWindow::on_m_pushButton_StartSample_clicked()
{
    if(m_Start_Simple)
    {
        // 判断时间
        auto iCurTime = QDateTime::fromString(LocalDateTime,"yyyy-MM-dd hh:mm:ss").toTime_t();
        auto iStartDateTime = ui->m_dateTimeEdit->dateTime().toTime_t();
        auto iEndDateTime = ui->m_dateTimeEdit_End->dateTime().toTime_t();

        if(!ui->m_radio_LocalDateTime->isChecked()&&iCurTime>iStartDateTime)
        {
            QMessageBox::information(this, "提示信息", "开始时间早于当前时间,请重新选择",QMessageBox::Ok);
            return;
        }
        // 格式化内存
        if(!ui->m_radio_LocalDateTime->isChecked()&&iStartDateTime>iEndDateTime)
        {
            QMessageBox::information(this, "提示信息", "开始时间晚于结束时间,请重新选择",QMessageBox::Ok);
            return;
        }

        if(ui->m_radio_LocalDateTime->isChecked()&&iStartDateTime>iEndDateTime)
        {
            QMessageBox::information(this, "提示信息", "开始时间早于结束时间,请重新选择",QMessageBox::Ok);
            return;
        }

        if (ui->m_radio_LocalDateTime->isChecked() && iEndDateTime < iCurTime)
        {
            QMessageBox::information(this, "提示信息", "结束时间晚于当前时间,请重新选择", QMessageBox::Ok);
            return;
        }

        uint iTotalSec = 0;
        if (ui->m_spinBox_Hour->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Hour->value() * 3600;
        }
        if (ui->m_spinBox_Minute->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Minute->value() * 60;
        }
        if (ui->m_spinBox_Second->isEnabled())
        {
            iTotalSec += ui->m_spinBox_Second->value();
        }
        if (iTotalSec <= 0)
        {
            QMessageBox::information(this, "提示信息", "时间间隔小于0,请重新选择", QMessageBox::Ok);
            return;
        }
        if (iTotalSec >= 65535)
        {
            QMessageBox::information(this, "提示信息", "最大采样间隔18小时12分钟15秒", QMessageBox::Ok);
            return;
        }

        // 用户是否立即采样
        QByteArray arrAA = ui->m_radio_LocalDateTime->isChecked()?"00":"01";
        if(arrAA=="00")
        {
            ui->m_dateTimeEdit->setDateTime(QDateTime::fromString(LocalDateTime,"yyyy-MM-dd hh:mm:ss"));
        }
        QMessageBox:: StandardButton result= QMessageBox::information(this, "提示信息", "是否清空内存",QMessageBox::Yes|QMessageBox::No);
        switch (result)
        {
        case QMessageBox::Yes:
            confirmDevice->serial_TD.write(QByteArray::fromHex("EB901500000000000000000000000000000000"));  // 464D54 格式化  464D54

            m_Start_Simple = false;
            ui->m_pushButton_StartSample->setText("停止");
            break;
        case QMessageBox::No:
            return;
            break;
        default:
            break;
        }
    }
    else if(!m_Start_Simple)
    {
        m_Start_Simple = true;
        ui->m_pushButton_StartSample->setText("启用");
        emit send_Stop_Sample();
        QTimer::singleShot(200, this, [=]() {emit send_Stop_Sample(); });
    }
}

void MainWindow::on_m_pbn_Save_Config_clicked()
{

    // 判断时间
    auto iCurTime = QDateTime::fromString(LocalDateTime, "yyyy-MM-dd hh:mm:ss").toTime_t();
    auto iStartDateTime = ui->m_dateTimeEdit->dateTime().toTime_t();
    auto iEndDateTime = ui->m_dateTimeEdit_End->dateTime().toTime_t();

    if (!ui->m_radio_LocalDateTime->isChecked() && iCurTime > iStartDateTime)
    {
        QMessageBox::information(this, "提示信息", "开始时间早于当前时间,请重新选择", QMessageBox::Ok);
        return;
    }
    // 格式化内存
    if (!ui->m_radio_LocalDateTime->isChecked() && iStartDateTime > iEndDateTime)
    {
        QMessageBox::information(this, "提示信息", "开始时间晚于结束时间,请重新选择", QMessageBox::Ok);
        return;
    }

    if (ui->m_radio_LocalDateTime->isChecked() && iStartDateTime > iEndDateTime)
    {
        QMessageBox::information(this, "提示信息", "开始时间早于结束时间,请重新选择", QMessageBox::Ok);
        return;
    }

    if (ui->m_radio_LocalDateTime->isChecked() && iEndDateTime < iCurTime)
    {
        QMessageBox::information(this, "提示信息", "结束时间晚于当前时间,请重新选择", QMessageBox::Ok);
        return;
    }

    uint iTotalSec = 0;
    if (ui->m_spinBox_Hour->isEnabled())
    {
        iTotalSec += ui->m_spinBox_Hour->value() * 3600;
    }
    if (ui->m_spinBox_Minute->isEnabled())
    {
        iTotalSec += ui->m_spinBox_Minute->value() * 60;
    }
    if (ui->m_spinBox_Second->isEnabled())
    {
        iTotalSec += ui->m_spinBox_Second->value();
    }
    if (iTotalSec <= 0)
    {
        QMessageBox::information(this, "提示信息", "时间间隔小于0,请重新选择", QMessageBox::Ok);
        return;
    }
    if (iTotalSec >= 65535)
    {
        QMessageBox::information(this, "提示信息", "最大采样间隔18小时12分钟15秒", QMessageBox::Ok);
        return;
    }

    // 用户是否立即采样
    QByteArray arrAA = ui->m_radio_LocalDateTime->isChecked() ? "00" : "01";
    if (arrAA == "00")
    {
        ui->m_dateTimeEdit->setDateTime(QDateTime::fromString(LocalDateTime, "yyyy-MM-dd hh:mm:ss"));
    }
    QMessageBox::StandardButton result = QMessageBox::information(this, "提示信息", "是否清空内存", QMessageBox::Yes | QMessageBox::No);
    switch (result)
    {
    case QMessageBox::Yes:
        confirmDevice->serial_TD.write(QByteArray::fromHex("EB901500000000000000000000000000000000"));  // 464D54 格式化  464D54

        m_Start_Simple = false;
        ui->m_pushButton_StartSample->setText("停止");
        // 800毫秒停止采样
        QTimer::singleShot(800, this, [=]() {emit send_Stop_Sample(); });
        break;
    case QMessageBox::No:
        return;
        break;
    default:
        break;
    }
}



void MainWindow::set_Btn_Status(QByteArray interval_data)
{
    if (interval_data.size() > 6)
    {
        sampleInterval = interval_data.mid(14, 4).toInt(nullptr, 16);
        int iSec = sampleInterval % 60;
        int iHour = sampleInterval / 3600;
        int iMin = sampleInterval % 3600 / 60;
        if (iHour > 0)
        {
            ui->m_radioButton_Hour->setChecked(true);
            ui->m_spinBox_Hour->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(true);
            ui->m_spinBox_Second->setEnabled(true);
        }
        else if (iMin > 0)
        {
            ui->m_radioButton_Minute->setChecked(true);
            ui->m_spinBox_Second->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(true);
            ui->m_spinBox_Hour->setEnabled(false);
        }
        else if (iSec > 0)
        {
            ui->m_radioButton_Second->setChecked(true);
            ui->m_spinBox_Second->setEnabled(true);
            ui->m_spinBox_Minute->setEnabled(false);
            ui->m_spinBox_Hour->setEnabled(false);

        }
        ui->m_spinBox_Hour->setValue(iHour);
        ui->m_spinBox_Minute->setValue(iMin);
        ui->m_spinBox_Second->setValue(iSec);

        interval_data.mid(0, 2) == "00" ? ui->m_radio_LocalDateTime->setChecked(true) : ui->m_radio_LocalDateTime->setChecked(false);
        
        QString startDate = "20" + interval_data.mid(2, 2) + "-" + interval_data.mid(4, 2) + "-" + interval_data.mid(6, 2) + " " + interval_data.mid(8, 2) + ":" + interval_data.mid(10, 2) + ":" + interval_data.mid(12, 2);
        QDateTime time = QDateTime::fromString(startDate, "yyyy-MM-dd hh:mm:ss");
        ui->m_dateTimeEdit->setDateTime(time);
        QString endDate = "20" + interval_data.mid(20, 2) + "-" + interval_data.mid(22, 2) + "-" + interval_data.mid(24, 2) + " " + interval_data.mid(26, 2) + ":" + interval_data.mid(28, 2) + ":" + interval_data.mid(30, 2);
        time = QDateTime::fromString(endDate, "yyyy-MM-dd hh:mm:ss");    
        ui->m_dateTimeEdit_End->setDateTime(time);
    }
    setSampleStatus_01(false);
    ui->m_pushButton_StartSample->setText("停止");
}

void MainWindow::set_Stop_After_Change_Status()
{
    setSampleStatus_01(true);
    ui->m_pushButton_StartSample->setText("启用");
    // 发送读取 下位机采样配置
    emit send_Read_Sample_Status();
    m_start_rotate->setEnabled(true);
}


void MainWindow::on_m_Use_Last_Config_clicked()
{
    emit send_Get_Sample_Config();
}

void MainWindow::on_m_pbn_DownLoad_clicked()
{
    // QBox = false;
    // read_config_file();
    //读一下配置
    confirmDevice->serial_TD.write(QByteArray::fromHex("EB901000000000000000000000000000000000"));  // 474354
    // 以上两行代码放开，下面一行代码注了
    QBox = true;

    if (QBox) {

        QTimer::singleShot(200, this, [=]() { emit send_Read_Flash(); });
        
    }
    else {
        // 提示用户没有找到文件
        QMessageBox::information(this, "提示信息", "没有配置文件", QMessageBox::Ok);
        return;
    }
#if 1
    if (m_pDialog == NULL)
    {
        m_pDialog = new QProgressDialog();
        m_pDialog->setWindowModality(Qt::ApplicationModal);   // 对本程序模态
        m_pDialog->setCancelButtonText(nullptr);
        m_pDialog->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint);
        m_pDialog->setLabelText("The Flash Data is Downloading...");
        m_pDialog->setRange(0, 100);
        m_pDialog->setValue(0);
        m_pDialog->setAutoReset(true);
        m_pDialog->setAutoClose(true);
        m_pDialog->show();
        //connect(m_pDialog,SIGNAL(canceled()),this,SLOT(cancelSlot()));
        disconnect(m_pDialog, SIGNAL(canceled()), m_pDialog, SLOT(cancel()));
    }    
#endif
    // 发送获取配置指令
    confirmDevice->serial_TD.write(QByteArray::fromHex("EB901300000000000000000000000000000000"));  // 474354
    qDebug() << QByteArray::fromHex("EB901300000000000000000000000000000000");
}

void MainWindow::read_config_file()
{
    //QFile file(":/config/config.ac");
    QFile file("./config/config.ac");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "文件没有打开";
        return;
    }
    QByteArray array = file.readAll();
    for (int i = 0; i < array.size(); i += 44)
    {
        QByteArray id = array.mid(i, 4);
        std::reverse(id.begin(), id.end());
        ids.append(id.toHex().toInt(nullptr, 16));
        qDebug() << "ids" << ids;
        QByteArray Tm = array.mid(i + 4, 8).data();
        Tms.append(Tm);

        QByteArray T0 = array.mid(i + 12, 8);
        CoefficientAs.append(T0);

        QByteArray T1 = array.mid(i + 20, 8);
        CoefficientBs.append(T1);

        QByteArray T2 = array.mid(i + 28, 8);
        CoefficientCs.append(T2);

        QByteArray T3 = array.mid(i + 36, 8);
        CoefficientDs.append(T3);
    }
    double invMatrix[][4] = { {-1.49159031063760, -0.615601881466894, -0.764849236567874, -0.177375156618825},
        {-0.742301837259857, 0.748076783703985, -1.402268969338759, -0.196053487807333},
        {-0.196053487807333, -0.192418510588264, -1.422375925091497, 1.419310150642549},
    {2.350457224002042, 0.888610425420721, 0.488193909859941, 0.291584373984183} };

    for (int i = 0; i < (array.size() / 44); i++)
    {
        double Encrypt[4];
        double UNEncrypt[4];
        double Tms_Data;
        memset(&Encrypt[0], 0x00, sizeof(double));
        memcpy(&Encrypt[0], CoefficientAs.at(i), sizeof(double));
        memcpy(&Encrypt[1], CoefficientBs.at(i), sizeof(double));
        memcpy(&Encrypt[2], CoefficientCs.at(i), sizeof(double));
        memcpy(&Encrypt[3], CoefficientDs.at(i), sizeof(double));
        matrix_vector_mult(invMatrix, Encrypt, UNEncrypt, 4, 4);

        DeviceConfig.append(ids.at(i));
        memcpy(&Tms_Data, Tms.at(i), sizeof(double));
        DeviceConfig.append(Tms_Data);
        for (int i = 0; i < 4; i++)
        {
            DeviceConfig.append(UNEncrypt[i]);
        }
    }

    for (int i = 0; i < ids.size(); i++)
    {
        if (QString::number(ids[i]) == m_Serial)
        {
            QBox = true;
            DeviceId = i;
        }
    }
}

void MainWindow::closeEvent(QCloseEvent* event)
{

    dockWidgetCTD_IM->closeDockWidgetDeal();
    // 在窗口关闭前执行一些操作,这里要更改波特率操作
    qDebug() << "window is closing";

    // 调用父类的 closeEvent 处理
    QMainWindow::closeEvent(event);
}

double MainWindow::vectors_dot_prod(const double* x, const double* y, int n)
{
    double res = 0.0;
    int i;
    for (i = 0; i < n; i++)
    {
        res += (x[i]) * (y[i]);
    }
    return res;
}



void MainWindow::matrix_vector_mult(const double mat[][4], const double* vec, double* result, int rows, int cols)
{ // in matrix form: result = mat * vec;
    int i;
    for (i = 0; i < rows; i++)
    {
        result[i] = vectors_dot_prod(mat[i], vec, cols);
    }
}



#if 1
void MainWindow::set_Down_Load(QByteArray arrData)
{

    qDebug() << "arrData.size()=" << arrData.size();
    //qDebug() << "arrData=" << arrData;
    QList<QByteArray> listArrDataFinal;
    QList<QByteArray> listArrData;
    QByteArray listArrData_1;
    if ((arrData.contains("010101435349"))|| (arrData.contains("01010154494d")))
    {
        listArrDataFinal.append(ByteSplit(arrData, "010101435349","01010154494d"));
    }
    else if (arrData.contains("010101535450"))
    {
        bOK = true;
    }
    for(auto &arrElement : listArrDataFinal)
    {
        //qDebug()<<"arrElement="<<arrElement;
        if("fcfcfc" == arrElement || arrElement.size() < 12 || "fefefe" == arrElement)
        {
            continue;
        }
        else if(arrElement.size() % 12 && !arrElement.contains("ffffffffffff") && !arrElement.contains("fffffffffffe") && !arrElement.contains("fffffffffefe") && !arrElement.contains("fffffffefefe"))
        {
            qDebug()<<"arrElement.size="<<arrElement.size()<<"arrElement.data="<<arrElement.data();
            QMessageBox::information(this, tr("Prompt"), tr("The downloaded data is error, some data have missed"));
            return;
        }
        m_arrLast = arrElement;
        int iSize = arrElement.size();
        //qDebug()<<"QDateTime"<<QDateTime::fromString("20" + arrElement.left(12),"yyyyMMddhhmmss")<<"QDateTime.toTime"<<QDateTime::fromString("20" + arrElement.left(12),"yyyyMMddhhmmss").toTime_t();
        m_iStartTime = 12 > iSize ? m_iStartTime : QDateTime::fromString("20" + arrElement.left(12),"yyyyMMddhhmmss").toTime_t();
        for(int iPos = 12;iPos < iSize;iPos += 12)
        {
            auto &&arrTemp = arrElement.mid(iPos,12);
            if(arrTemp.contains("010101535450") || "ffffffffffff" == arrTemp || "fffffffffffe" == arrTemp || "fffffffffefe" == arrTemp || "fffffffefefe" == arrTemp)
            {
                bOK = true;
                break;
            }
            else if(12 > arrTemp.size())
            {
                m_arrRemain = arrTemp;
                continue;
            }

            auto iTemperature = arrTemp.left(6).toInt(nullptr,16);
            auto iPressure = arrTemp.right(6).toInt(nullptr,16);
            if(0xEE0000 < iPressure)
            {
                iPressure = iPressure - 0x1000000;
            }

			double dK = iPressure * 1.0 / pow(2, 24);
			double dH = iTemperature * 1.0 / pow(2, 24);
			double dN = log(pow(2, 24) / iTemperature - 1);
			double dPressure = m_dP[0] + m_dP[1] * dK + m_dP[2] * pow(dK, 2) + m_dP[3] * pow(dK, 3);
			double dTemperature = 1 / (m_dT[0] + m_dT[1] * dN + m_dT[2] * pow(dN, 2) + m_dT[3] * pow(dN, 3)) - 273.15;

#if 1           
            m_iBarVal_count = 100 * ++m_iBarVal / (m_iPageQuantity * 39);
            if (((m_iBarVal_count%5) == 0)&&(m_iBarVal_count>=5)&&(m_iBarVal_count <= 99))
            {
                if (m_iBarVal_count_old != m_iBarVal_count)
                {
                    m_iBarVal_count_old = m_iBarVal_count;
                    if (NULL != m_pDialog)
                    {
                        _sleep(1);
                        m_pDialog->setValue(m_iBarVal_count);  // m_iPageQuantity 代表页数 * 39 = 条数
                    }
                }
            }
#endif
			m_vecTemperature.push_back(dTemperature);
			m_vecDateTime.push_back(m_iStartTime);
			m_vecPressure.push_back(dPressure);

			m_iStartTime += sampleInterval;
			m_vecN.push_back(dH);
			m_vecK.push_back(dK);
        }
    }
    if (bOK)
    {
        bOK = false;
#if 1
        m_iBarVal = 0;  // 分子置零
        m_pDialog->setValue(100);
        if (NULL != m_pDialog)
        {
            m_pDialog->hide();
            delete m_pDialog;
            m_pDialog = NULL;
        }
#endif
        m_Heart_timer->start();

        // 修复过的数据
        // SaveDownFile();

        // 原始数据
        OriginSaveDownFile();
    }
}
#endif  

// 下载原始数据
void MainWindow::OriginSaveDownFile()
{
    auto&& strFilePath = QFileDialog::getSaveFileName(this, tr("Save download data"),
       ui->m_labelSerial->text() + "_" + "20" + ui->m_dateTimeEdit->dateTime().toString("yyMMddhhmmss"), tr("DAT File(*.dat);;RAW Files(*.raw)"));
    //auto&& strFilePath = QFileDialog::getSaveFileName(this, tr("Save download data"),
    //    ui->m_labelSerial->text() + "_" + QDateTime::fromTime_t(m_vecDateTime.at(0)).toString("yyyyMMddhhmmss"), tr("DAT File(*.dat);;RAW Files(*.raw)"));
    QFile clsFile(strFilePath);
    if (strFilePath.isEmpty() || !clsFile.open(QIODevice::WriteOnly))
    {
        m_vecN.clear();
        m_vecK.clear();
        m_vecDateTime.clear();
        m_vecPressure.clear();
        m_vecTemperature.clear();

        return;
    }
#if 1
    if (NULL == m_pDialog)
    {
        m_pDialog = new QProgressDialog();
        m_pDialog->setWindowModality(Qt::ApplicationModal);   // 对本程序模态
        m_pDialog->setCancelButtonText(nullptr);
        m_pDialog->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint);
        m_pDialog->setRange(0, 100);
        m_pDialog->setValue(0);
        m_pDialog->setAutoClose(true);
        // 设置进度条小于四秒也显示
        m_pDialog->setMinimumDuration(0);
        m_pDialog->show();
        disconnect(m_pDialog, SIGNAL(canceled()), m_pDialog, SLOT(cancel()));
    }
#endif
    m_pDialog->setLabelText("The Download Data is Saving...");
    m_pDialog->setValue(0);
    QString strText = "%Model\t\t\t\t\t\t\t\t\t" + ui->label_type->text() + "\n";
    strText += "%Serial Number\t\t\t\t\t\t\t\t" + ui->m_labelSerial->text() + "\n";
    strText += "%Version Number\t\t\t\t\t\t\t\t" + ui->m_labelSoftwareVersion->text() + "\n";
    strText += "%RTC time\t\t\t\t\t\t\t\t" + ui->m_labelDeviceTime->text() + "\n";           // 设备时间
    strText += "%Start time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit->text() + "\n";  // 数据包的第一贞时间
    strText += "%End time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit_End->text() + "\n";   // 数据包的最后一贞时间
    // strText += "%Start time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit->dateTime().toString("yyyy-MM-dd hh:mm:ss") + "\n";  
    // strText += "%End time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit_End->dateTime().toString("yyyy-MM-dd hh:mm:ss") + "\n";   

    strText += "%Immediately?\t\t\t\t\t\t\t\t" + QString(m_bIM ? "Y" : "N") + "\n";
    strText += "%Sample interval\t\t\t\t\t\t\t\t" + QString("%1").arg(sampleInterval) + "\n";
    strText += "%Sample interval unit\t\t\t\t\t\t\tSec\n";
    strText += QString("%Temperature Coefficients\n#%1\n#%2\n#%3\n#%4\n").arg(m_dT[0], 0, 'R', 15).arg(m_dT[1], 0, 'R', 15).arg(m_dT[2], 0, 'R', 15).arg(m_dT[3], 0, 'R', 15);
    strText += QString("%Pressure Coefficients\n#%1\n#%2\n#%3\n#%4\n").arg(m_dP[0], 0, 'R', 15).arg(m_dP[1], 0, 'R', 15).arg(m_dP[2], 0, 'R', 15).arg(m_dP[3], 0, 'R', 15);
    if (strFilePath.endsWith(".dat"))
    {
        strText += QString("%Datetime\t\t\t\t\t\t\tTemperature\t\t\t\t\tPressure\t\t\t\t\tDeep\n");
        for (int index = 0; index < m_vecDateTime.size(); index++)
        {
            strText += QDateTime::fromTime_t(m_vecDateTime.at(index)).toString("yyyy-MM-dd hh:mm:ss") + QString("\t\t%1\t\t\t\t\t\t\t%2\t\t\t\t\t\t%3\n").arg(m_vecTemperature[index], 0, 'R', 4).arg(m_vecPressure[index], 0, 'R', 2).arg(m_vecPressure[index] - 10.1325 / (1.0281 * 0.980665), 0, 'R', 2);
            clsFile.write(strText.toUtf8());
            strText.clear();
            m_iBarVal_count = 100 * index / m_vecDateTime.size();
            if (((m_iBarVal_count % 5) == 0) && (m_iBarVal_count >= 5) && (m_iBarVal_count <= 99))
            {
                if (m_iBarVal_count_old != m_iBarVal_count)
                {
                    m_iBarVal_count_old = m_iBarVal_count;
                    if (NULL != m_pDialog)
                    {
                        _sleep(10);
                        m_pDialog->setValue(m_iBarVal_count);  // m_iPageQuantity 代表页数 * 39 = 条数
                }
            }
        }
    }
}
    if (strFilePath.endsWith(".raw"))
    {
        strText += QString("%Datetime\t\t\t\t\t\t\tTemperature\t\t\t\t\tPressure\n");

        for (long iValue = 0; iValue < m_vecDateTime.size(); iValue++)
        {
            strText += QDateTime::fromTime_t(m_vecDateTime.at(iValue)).toString("yyyy-MM-dd hh:mm:ss") + QString("\t\t%1\t\t%2\n").arg(m_vecN[iValue] * 13, 0, 'R', 15).arg(m_vecK[iValue], 0, 'R', 15);
            clsFile.write(strText.toUtf8());
            strText.clear();
            m_iBarVal_count = 100 * iValue / m_vecDateTime.size();
            if (((m_iBarVal_count % 5) == 0) && (m_iBarVal_count >= 5) && (m_iBarVal_count <= 99))
            {
                if (m_iBarVal_count_old != m_iBarVal_count)
                {
                    m_iBarVal_count_old = m_iBarVal_count;
                    if (NULL != m_pDialog)
                    {
                        _sleep(10);
                        m_pDialog->setValue(m_iBarVal_count);  // m_iPageQuantity 代表页数 * 39 = 条数
                    }
                }
            }
        }
    }
#if 1
    if (NULL != m_pDialog)
    {
        m_pDialog->hide();
        delete m_pDialog;
        m_pDialog = NULL;
    }
#endif
    clsFile.close();
    m_vecN.clear();
    m_vecN.clear();
    m_vecK.clear();
    m_vecDateTime.clear();
    m_vecPressure.clear();
    m_vecTemperature.clear();
    // 清空读文件容器
    // setReadFileStatus();
}

// 下载修复后的数据
void MainWindow::SaveDownFile()
{
    auto&& strFilePath = QFileDialog::getSaveFileName(this,tr("Save download data"), ui->m_labelSerial->text() + "_" + "20" + ui->m_dateTimeEdit->dateTime().toString("yyMMddhhmmss"),tr("DAT File(*.dat);;RAW Files(*.raw)"));
    QFile clsFile(strFilePath);
    if (strFilePath.isEmpty()|| !clsFile.open(QIODevice::WriteOnly))
    {
        m_vecN.clear();
        m_vecK.clear();
        m_vecDateTime.clear();
        m_vecPressure.clear();
        m_vecTemperature.clear();

        return;
    }
#if 1
    if (NULL == m_pDialog)
    {
        m_pDialog = new QProgressDialog();
        m_pDialog->setWindowModality(Qt::ApplicationModal);   // 对本程序模态
        m_pDialog->setCancelButtonText(nullptr);
        m_pDialog->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint);
        m_pDialog->setRange(0, 100);
        m_pDialog->setValue(0);
        //m_pDialog->setAutoReset(true);
        m_pDialog->setAutoClose(true);
        // 设置进度条小于四秒也显示
        m_pDialog->setMinimumDuration(0);
        m_pDialog->show();
        disconnect(m_pDialog, SIGNAL(canceled()), m_pDialog, SLOT(cancel()));
    }
#endif
    m_pDialog->setLabelText("The Download Data is Saving...");
    m_pDialog->setValue(0);
    QString strText = "%Model\t\t\t\t\t\t\t\t\t" + ui->label_type->text() + "\n";
    strText += "%Serial Number\t\t\t\t\t\t\t\t" + ui->m_labelSerial->text() + "\n";
    strText += "%Version Number\t\t\t\t\t\t\t\t" + ui->m_labelSoftwareVersion->text() + "\n";
    strText += "%RTC time\t\t\t\t\t\t\t\t" + ui->m_labelDeviceTime->text() + "\n";

    // strText += "%Start time\t\t\t\t\t\t\t\t" + QDateTime::fromTime_t(m_vecDateTime.at(0)).toString("yyyy-MM-dd hh:mm:ss") + "\n";
    // strText += "%End time\t\t\t\t\t\t\t\t" + QDateTime::fromTime_t(m_vecDateTime.last()).toString("yyyy-MM-dd hh:mm:ss") + "\n";

    strText += "%Start time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit->text() + "\n";
    strText += "%End time\t\t\t\t\t\t\t\t" + ui->m_dateTimeEdit_End->text() + "\n";

    strText += "%Immediately?\t\t\t\t\t\t\t\t" + QString(m_bIM ? "Y" : "N") + "\n";
    strText += "%Sample interval\t\t\t\t\t\t\t\t" + QString("%1").arg(sampleInterval) + "\n";
    strText += "%Sample interval unit\t\t\t\t\t\t\tSec\n";

    if (strFilePath.endsWith(".dat"))
    {
        strText += QString("%Datetime\t\t\t\tTemperature\t\t\tPressure\n");
        for (int index=0;index < m_vecDateTime.size();index++)
        {
            double err = (DeviceConfig.at(DeviceId * 6+2)*(pow((m_vecTemperature[index]- DeviceConfig.at(DeviceId * 6 + 1)),3))) + (DeviceConfig.at(DeviceId * 6 + 3) *(pow((m_vecTemperature[index]- DeviceConfig.at(DeviceId * 6 + 1)),2))) + (DeviceConfig.at(DeviceId * 6 + 4)*(m_vecTemperature[index]- DeviceConfig.at(DeviceId * 6 + 1))) + DeviceConfig.at(DeviceId * 6 + 5);
            double Pc = m_vecPressure[index] - err;
            strText += QDateTime::fromTime_t(m_vecDateTime.at(index)).toString("yyyy-MM-dd hh:mm:ss") + QString("\t\t\t\t%1\t\t\t\t%2\n").arg(m_vecTemperature[index], 0, 'R', 4).arg(Pc,0,'R',4);
            clsFile.write(strText.toUtf8());
            strText.clear();
            m_iBarVal_count = 100 * index / m_vecDateTime.size();
            if (((m_iBarVal_count % 5) == 0) && (m_iBarVal_count >= 5) && (m_iBarVal_count <= 99))
            {
                if (m_iBarVal_count_old != m_iBarVal_count)
                {
                    m_iBarVal_count_old = m_iBarVal_count;
                    if (NULL != m_pDialog)
                    {
                        _sleep(10);
                        m_pDialog->setValue(m_iBarVal_count);  // m_iPageQuantity 代表页数 * 39 = 条数
                    }
                }
            }
        }
    }
    if (strFilePath.endsWith(".raw"))
    {
        strText += QString("%Datetime\t\t\t\t\t\t\tTemperature\t\t\t\t\tPressure\n");
        
        for (long iValue = 0; iValue< m_vecDateTime.size();iValue++)
        {
            strText += QDateTime::fromTime_t(m_vecDateTime.at(iValue)).toString("yyyy-MM-dd hh:mm:ss") + QString("\t\t%1\t\t%2\n").arg(m_vecN[iValue] * 13, 0, 'R', 15).arg(m_vecK[iValue], 0, 'R', 15);
            clsFile.write(strText.toUtf8());
            strText.clear();
            m_iBarVal_count = 100 * iValue / m_vecDateTime.size();
            if (((m_iBarVal_count % 5) == 0) && (m_iBarVal_count >= 5) && (m_iBarVal_count <= 99))
            {
                if (m_iBarVal_count_old != m_iBarVal_count)
                {
                    m_iBarVal_count_old = m_iBarVal_count;
                    if (NULL != m_pDialog)
                    {
                        _sleep(10);
                        m_pDialog->setValue(m_iBarVal_count);  // m_iPageQuantity 代表页数 * 39 = 条数
                    }
                }
            }
        }
    }
#if 1
    if (NULL != m_pDialog)
    {
        m_pDialog->hide();
        delete m_pDialog;
        m_pDialog = NULL;
    }
#endif
    clsFile.close();
    m_vecN.clear();
    m_vecN.clear();
    m_vecK.clear();
    m_vecDateTime.clear();
    m_vecPressure.clear();
    m_vecTemperature.clear();
}


QList<QByteArray> MainWindow::ByteSplit(QByteArray &arrByte, const QByteArray &arrSplit_1, const QByteArray& arrSplit_2)
{
    QList<QByteArray> listArrData;
    while(true)
    {
        auto iPos_1 = arrByte.indexOf(arrSplit_1);
        auto iPos_2 = arrByte.indexOf(arrSplit_2);
        if((0 > iPos_1)&&(0> iPos_2))
        {
            break;
        }
        else if(0 <= iPos_1)
        {
            listArrData.push_back(arrByte.left(iPos_1));
            arrByte.remove(0, iPos_1 + 12);
        }
        else if (0 <= iPos_2)
        {
            listArrData.push_back(arrByte.left(iPos_2));
            arrByte.remove(0, iPos_2 + 12);
        }
    }

    listArrData.push_back(arrByte);
    return std::move(listArrData);
}

void MainWindow::set_Bar_WidgetCenter(QWidget *pWidget)
{
    if(!pWidget)
    {
        return;
    }
    auto &&clsPos = pWidget->pos();
    setGeometry(clsPos.x()+pWidget->width() / 2-width() / 2,clsPos.y()+pWidget->height() / 2-height() / 2,width(),height());
}




